Syntaxerror json parse error unrecognized token

Issue Description JSON Parse error: Unrecognized token (no JSON shown) Steps to Reproduce / Code Snippets Not sure. I get zero information in the stack trace or logs that points to my own code. Thi...

This is what i get as logs
Error occurs at response.json() call. Interesting thing is, this call works fine if i set chrome remote debug on. It works fine in iOS 10.0 (didn’t test in earlier version)

11-01 08:53:27.036 32587  4288 I ReactNativeJS: { type: 'default',
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   status: 200,
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   ok: true,
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   statusText: undefined,
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   headers: 
11-01 08:53:27.036 32587  4288 I ReactNativeJS:    { map: 
11-01 08:53:27.036 32587  4288 I ReactNativeJS:       { date: [ 'Tue, 01 Nov 2016 03:23:21 GMT' ],
11-01 08:53:27.036 32587  4288 I ReactNativeJS:         server: [ 'Microsoft-HTTPAPI/2.0' ],
11-01 08:53:27.036 32587  4288 I ReactNativeJS:         'content-type': [ 'application/json' ],
11-01 08:53:27.036 32587  4288 I ReactNativeJS:         'content-length': [ '187' ] } },
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   url: 'http://xx.xx.xx.xx/Service/json/xxxx',
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   _bodyInit: '{rn  "Command": 20020,rn  "Id": 216,rn  "Name": "Tester",rn  "Email": "cc@cc.com",rn  "Tel": "(012) 345-6712",rn  "Pass": null,rn  "IsActive": true,rn  "HasAccount": falsern}',
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   _bodyText: '{rn  "Command": 20020,rn  "Id": 216,rn  "Name": "Tester",rn  "Email": "cc@cc.com",rn  "Tel": "(012) 345-6712",rn  "Pass": null,rn  "IsActive": true,rn  "HasAccount": falsern}' }

Above is the response which i get from the API call

11-01 08:53:27.042 32587  4288 I ReactNativeJS: { [SyntaxError: JSON Parse error: Unrecognized token '?']
11-01 08:53:27.042 32587  4288 I ReactNativeJS:   line: 30380,
11-01 08:53:27.042 32587  4288 I ReactNativeJS:   column: 10,
11-01 08:53:27.042 32587  4288 I ReactNativeJS:   sourceURL: 'http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false' }

ADMIN BUG? SyntaxError: JSON Parse error: Unrecognized token


When accessing the customer form from the customer list, i.e. when trying to edit a customer, opencart returns this message and logs me out:

SyntaxError: JSON Parse error: Unrecognized token ‘<‘
OK
<!DOCTYPE html>
<html dir=»ltr» lang=»en»>
<head>
<meta charset=»UTF-8″ />
<title>Administration</title>
<base href=»http://red-snake.co.uk/dos/admin/» />
<link rel=»stylesheet» type=»text/css» href=»view/stylesheet/stylesheet.css» />
<link rel=»stylesheet/less» type=»text/css» href=»less/styles.less» />
<link rel=»stylesheet» type=»text/css» href=»view/stylesheet/font-awesome.min.css»>
<link rel=»stylesheet» type=»text/css» href=»view/stylesheet/font-awesome.min.css»>
<link href=’http://fonts.googleapis.com/css?family=Monda’ rel=’stylesheet’ type=’text/css’>
<!—[if IE 7]>
<link rel=»stylesheet» type=»text/css» href=»view/stylesheet/font-awesome-ie7.min.css»>
<![endif]—><script type=»text/javascript» src=»view/javascript/jquery/jquery-1.7.1.min.js»></script>
<script type=»text/javascript» src=»view/javascript/jquery/ui/jquery-ui-1.8.16.custom.min.js»></script>
<link type=»text/css» href=»view/javascript/jquery/ui/themes/ui-lightness/jquery-ui-1.8.16.custom.css» rel=»stylesheet» />
<script type=»text/javascript» src=»view/javascript/jquery/tabs.js»></script>
<script type=»text/javascript» src=»view/javascript/jquery/superfish/js/superfish.js»></script>
<script type=»text/javascript» src=»view/javascript/common.js»></script>
<script type=»text/javascript» src=»view/javascript/metro.js»></script>
<script type=»text/javascript»>
//——————————————
// Confirm Actions (delete, uninstall)
//——————————————
$(document).ready(function(){
// Confirm Delete
$(‘#form’).submit(function(){
if ($(this).attr(‘action’).indexOf(‘delete’,1) != -1) {
if (!confirm(‘Delete/Uninstall cannot be undone! Are you sure you want to do this?’)) {
return false;
}
}
});

// Confirm Uninstall
$(‘a’).click(function(){
if ($(this).attr(‘href’) != null && $(this).attr(‘href’).indexOf(‘uninstall’, 1) != -1) {
if (!confirm(‘Delete/Uninstall cannot be undone! Are you sure you want to do this?’)) {
return false;
}
}
});
});
</script>
</head>
<body>
<div id=»container»>
<div id=»header»>
</div>
<div id=»content»>
<div class=»box loginbox» style=»width: 30%; min-height: 20%; margin-top: 40px; margin-left: auto; margin-right: auto;»>
<div class=»content login» style=»min-height: 150px; overflow: hidden;»>
<form action=»http://red-snake.co.uk/dos/admin/index. … mmon/login» method=»post» enctype=»multipart/form-data» id=»form»>
<table style=»width: 100%;» class=»login»>
<tr>
<td>
<h1 class=»icon-lock»> Log In</h1>
</td>
</tr>
<tr>
<td>
<label>Username:</label>
<input type=»text» name=»username» value=»» class=»login» />
<br />
<br />
<label class=»login»>Password:</label>
<input type=»password» name=»password» value=»» class=»login» />
<br />
<ul class=»login»>
<li><a href=»http://red-snake.co.uk/dos/admin/index. … /forgotten»> Forgotten Your Password?</a></li>
<li class=»icon-signin»><a onclick=»$(‘#form’).submit();» class=»button»>Login</a></li>
</ul>
</td>
</tr>
</table>
<input type=»hidden» name=»redirect» value=»http://red-snake.co.uk/dos/admin/index. … try_id=222″ />
</form>
</div>

</div>

</div>
<script type=»text/javascript»><!—
$(‘#form input’).keydown(function(e) {
if (e.keyCode == 13) {
$(‘#form’).submit();
}
});
//—></script>

I’m not a big on opencart, so don’t really know where to start! Can someone help me please?

Many thanks,

Ed

Re: ADMIN BUG? SyntaxError: JSON Parse error: Unrecognized t


Post

by butte » Sun Apr 28, 2013 4:17 am

It appears that you mean the error message was immediately followed by all of that code. I do not recall encountering any «JSON Parse error» that long.

The error message itself, SyntaxError: JSON Parse error: Unrecognized token ‘<‘, appears to be telling you that it sprang from an unmated < whose > was nowhere to be found. Did you put «<» into a box? That could have derailed the code upon processing that < along with usual machine-readable syntax and punctuation. (In that event you inserted a benign example of user code injection: you’ve already seen day-to-day that operating systems will frequently not let you use several punctuation marks that are reserved for their own uses, and finding ways to sneak them in is actually an avenue for user code injection.)

Re: ADMIN BUG? SyntaxError: JSON Parse error: Unrecognized t


Post

by Daniel » Sun Apr 28, 2013 12:28 pm

ERROR IN THE BACKGROUND. you need to tell us what info you are sending.


OpenCart®
Project Owner & Developer.


User avatar


Re: ADMIN BUG? SyntaxError: JSON Parse error: Unrecognized t


Post

by stevchenks » Sun Apr 28, 2013 11:48 pm

Hi butte and Daniel,

To clarify which part of the system i’m coming from to get this message, I am editing a customer having clicked on «edit» on the customer list template.

As soon as I’m directed to the customer form template, the message appears and I am logged out.

Butte: I see some sense in what you are saying, however in my head I would have had to have change the hyperlink value and the parameters that get sent with it? I have looked on the presentation template and the php/html hyperlink code appears to be valid:

Code: Select all

              <td class="right"><?php foreach ($customer['action'] as $action) { ?>
                [ <a href="<?php echo $action['href']; ?>"><?php echo $action['text']; ?></a> ]
                <?php } ?></td>

So that would mean the error would lie in the controller part of the template, when the «<?php echo $action[‘href’]; ?>» is calling the relevant hyperlink, yes?

Here is the code for that part in the controller:

Code: Select all

				
$action[] = array(
text' => $this->language->get('text_edit'),
'href' => $this->url->link('sale/customer/update', 'token=' . $this->session->data['token'] . '&customer_id=' . $result['customer_id'] . $url, 'SSL')
			);

I hope that helps, and allows to you help me further?

Daniel: Is that more clear?

Many thanks,

Ed

Re: ADMIN BUG? SyntaxError: JSON Parse error: Unrecognized t


Post

by stevchenks » Mon Apr 29, 2013 12:33 am

Just to add to this issue,

I just did a clean install as I couldn’t find anything wrong with the code (admittedly I’m not a whizz at this, but I’d like to think I had some knowledge).

Either way after the clean install, the same problem persisted.

So — to me thats a bug.

Re: ADMIN BUG? SyntaxError: JSON Parse error: Unrecognized t


Post

by stevchenks » Mon Apr 29, 2013 12:43 am

These are screenshots of the error.

Again this is after a fresh install, so completely unedited code.

Thanks,

Ed

Attachments

Screen Shot 2013-04-28 at 17.42.37.png

Error Message — Screen Shot 2013-04-28 at 17.42.37.png (308.4 KiB) Viewed 4076 times

Screen Shot 2013-04-28 at 17.42.35.png

Screen I proceed to — Screen Shot 2013-04-28 at 17.42.35.png (203.8 KiB) Viewed 4076 times

Screen Shot 2013-04-28 at 17.41.07.png

Customer List Example — Screen Shot 2013-04-28 at 17.41.07.png (185.89 KiB) Viewed 4076 times

Re: ADMIN BUG? SyntaxError: JSON Parse error: Unrecognized t


Post

by butte » Mon Apr 29, 2013 1:41 am

What I had in mind is irrelevant BECAUSE you didn’t even get far enough to input a stray machine character via a box. The thought was, IF you had inadvertently injected a machine character (such as an unmated <), then the stream of code in processing could have been looking for the mate, or have gone wild if it was sent somewhere else entirely in execution. We now see that you didn’t get that far, stevchenks, so the thought doesn’t matter.

Any «JSON Parse error» can be maddening but usually or often leads attention to its own cause. That yours adds «OK» and goes on to respond at great length is particularly curious as to why it even wanted to give a partial «generated source» from top (starting with doctype, yet) down through the head and the upper body to the end of the second script. That suggests that perhaps it’s trying to say to look at the lower script. The upper script speaks to record deletion («confirm [ . . . ] cannot be undone»). The lower script speaks to a keyCode 13.

That appears not to matter, however, since with all of it in plain view Daniel’s immediate response was background error.

For what it might be worth (solution DOESN’T apply here), link compliments of uksitebuilder in an older thread, see
http://forum.opencart.com/viewtopic.php?f=133&t=45863 at
«multiple ajax callbacks causing file write locking which would throw hidden errors in the background» . . . somewhere.

Search «JSON Parse error: Unrecognized token ‘<‘» (with the outer quotation marks) yields perhaps surprising only «About 178 results (0.27 seconds)» at
http://www.google.com/search?q=%22JSON+ … encart.com
presenting an array of contexts for the same thrown error (token, but differing after «OK»).

Who is online

Users browsing this forum: No registered users and 4 guests

помогите разобраться, при оформлении заказа появляется вот такое ругательство:

SyntaxError: JSON Parse error: Unrecognized token ‘<‘ OK Notice: Undefined index: products in /var/www/u0522611/data/www/ххх/catalog/controller/extension/module/notificationTelegram.php on line 105Notice: Undefined index: products in /var/www/u0522611/data/www/ххх/catalog/controller/extension/module/notificationTelegram.php on line 105Notice: Undefined index: products in /var/www/u0522611/data/www/ххх/catalog/controller/extension/module/notificationTelegram.php on line 105{«redirect»:»http://ххх/index.php?route=checkout/success»}

код:

<?php
class ControllerExtensionModuleNotificationTelegram extends Controller {

        
    public function sendOrderAlert(&$route, &$data, &$output) {

        $order_id = $data[0];
        $this->load->model(‘checkout/order’);
        $order_info = $this->model_checkout_order->getOrder($order_id);

        $this->load->model(‘setting/setting’);
        $setting = $this->model_setting_setting->getSetting(‘module_notificationTelegram’);

        if (isset($setting[‘module_notificationTelegram_order_alert’])) {

            
            $this->load->model(‘account/order’);
            if (count($this->model_account_order->getOrderHistories($order_id)) <= 1) {
                $message = $this->replaceMessage($setting[‘module_notificationTelegram_meassage’],$order_info);
//                  $message .= $this->buldArray($order_info);

                $this->sendMessagetoTelegam($message);

                if (strpos(strtolower($setting[‘module_notificationTelegram_meassage’]), ‘{products}’) !== false) {
                    $order_products = $this->model_checkout_order->getOrderProducts($order_id);
                    $products = $this->bulidProducts($order_products);
                    $this->sendMessagetoTelegam($products);

                }
            }

            
        }

        
    }

    
    public function sendAccountAlert(&$route, &$data, &$output) {
        $this->load->model(‘setting/setting’);
        $setting = $this->model_setting_setting->getSetting(‘module_notificationTelegram’);
        if (isset($setting[‘module_notificationTelegram_customer_alert’])) {

            $message = $this->replaceMessage($setting[‘module_notificationTelegram_new_account_meassage’],$data[0]);
            $this->sendMessagetoTelegam( $message);

            
        }
    }

    
    public function sendReturnProductAlert(&$data,&$output) {
        $this->load->model(‘setting/setting’);
        $setting = $this->model_setting_setting->getSetting(‘module_notificationTelegram’);
        if (isset($setting[‘module_notificationTelegram_return_alert’])) {

            
            $message = «Return request n «;
            $this->sendMessagetoTelegam( $message);
        }
    }

    
    
    //Send  message To notificationTelegram
    public function sendMessagetoTelegam($msg) {

        
        $this->load->model(‘setting/setting’);
        $setting = $this->model_setting_setting->getSetting(‘module_notificationTelegram’);

        
        //print_r($setting);
        $botToken = $setting[‘module_notificationTelegram_boot_token’];
        $website = «https://api.telegram.org/bot» . $botToken;
        $chatIds = $setting[‘module_notificationTelegram_chat_ids’];  //Receiver Chat Id

        
        if (is_array($chatIds)) {
            foreach ($chatIds as $val) {
                $this->initMessage($botToken, $val, $msg);
            }
        } else {
            $this->initMessage($botToken, $chatIds, $msg);
        }
    }
    private function initMessage($botToken, $chatID, $msg) {

        
        $website = «https://api.telegram.org/bot» . $botToken;

        
        $params = [
            ‘chat_id’ => $chatID,
            ‘text’ => $msg,
        ];
        $ch = curl_init($website . ‘/sendMessage’);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);            
    }

    
    public function buldArray($arr) {
        if (is_array($arr)) {
            $dataAttributes = array_map(function ($value, $key) {
                return @»$key —> $value  n»;
            }, array_values($arr), array_keys($arr));

            
            return $dataAttributes = implode(‘ ‘, $dataAttributes);
        }
    }

    
    public function replaceMessage($string,$arr) {
        return   $str = preg_replace_callback(‘/{(w+)}/’, function($match) use($arr) {
            return $arr[$match[1]];
        }, $string );

        
    }

    
    protected function  bulidProducts($products){

        $pr = array();

        foreach ($products as $product){
            $pr[] = «Name : $product[name]  n    Price: $product[price] n qty : $product[quantity] «;
        }

        return implode(«——- n»,$pr);

        
    }

        
}

Introduction

A common issue that I see when working with front-end JavaScript heavy apps is the dreaded “SyntaxError Unexpected Token in JSON” error! Now this error can be of the form:

SyntaxError: Unexpected token < in JSON at position 0

SyntaxError: Unexpected end of JSON input

syntaxerror: unexpected token '<', "<!doctype "... is not valid json

The error “SyntaxError Unexpected Token in JSON” appears when you try to parse content (for example — data from a database, api, etc), but the content itself is not JSON (could be XML, HTML, CSV) or invalid JSON containing unescaped characters, missing commas and brackets.

There are a few things you can try to fix this error:

  1. Check that the content you are trying to parse is JSON format and not HTML or XML

  2. Verify that there are no missing or extra commas.

  3. Make sure to check for unescaped special characters.

  4. Check for mismatched brackets or quotes.

  5. Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors.

1. Check that the content you are trying to parse is JSON format and not HTML or XML

A common reason why the error “SyntaxError Unexpected Token in JSON” comes up is that we are trying to parse content that is not even JSON.

Consider the following front-end JavaScript code:

  

fetch('https://localhost:3000/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // Use the data here
  })

In the above example, the fetch() function is being used to retrieve data from a API that returns JSON format — in this case https://localhost:3000/data.

The fetch() function then returns a promise, and when that promise resolves, we handle that with the response.json() method. This just takes our JSON response and converts it to a JSON object to be used!

After that we just console.log out the data object

Now for the server-side of things, look on to our Node JS route that returns the JSON /data

  

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'text/html');  Not returning JSON.
    res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);

We can see that it is setting the Header as text/html. This will give you the error:

syntaxerror: unexpected token '<', "<!doctype "... is not valid json

This is because we are trying to parse the content with JSON.parse() or in our case response.json() and receiving a HTML file!

To fix this, we just need to change the returned header to res.setHeader('Content-Type', 'application/json'):

  

...
var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json'); ✔️ Returning JSON.
    res.end(JSON.stringify({ a: 1 }));
});
...

Whats Content-Type request header anyway?

Pretty much every resource on the internet will need to have a type (similar to how your file system contains file types like images, videos, text, etc).
This is known as a MIME type (Multipurpose Internet Mail Extension)

Browsers need to know what content type a resource is so that it can best handle it. Most modern browsers are becoming good at figuring out which content type a resource is, but its not always 100% correct.

That is why still need to explicitly specify our request header content-type!

syntaxerror: unexpected token ‘<’, “<!doctype “… is not valid json

This error also comes up when your API is returning invalid error pages such as 404/500 HTML pages. Since HTML usually starts with a “less than” tag symbol (<) and JSON is not valid with < tags, it will through this error.

For example, when everything is working find, your node API will happily return JSON. However when it fails with a 500 internal error, it could return a custom HTML error page!
In this case, when you try to do JSON.parse(data) you will get the syntaxerror: unexpected token '<', "<!doctype "... is not valid json.

Additionally, check that you are calling the correct API url. As an example, lets say the API that returns JSON is using the /data route. If you misspelt this, you could be redirected to a 404 HTML page instead!

Tip: Use appropriate error handlers for non-JSON data

If you are using fetch() to retrieve your data, we can add a catch handler to give meaningful error messages to the user:

  

fetch('https://localhost:3000/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // Use the data here
  })
  .catch(error => console.error(error)); /*✔️ Friendly error message for debugging! */

If you are using JSON.parse() we can do this in a try/catch block as follows:

  

try {
    JSON.parse(data);
}
catch (error) {
    console.log('Error parsing JSON:', error, data); /*✔️ Friendly message for debugging ! */
}

JSON objects and arrays should have a comma between each item, except for the last one.

  

{
    "name": "John Smith"
    "age": 30
    "address": {
        "street": "123 Main St"
        "city": "Anytown"
        "state": "USA"
    }
}

This JSON object will throw a “syntaxerror unexpected token” error because there is no comma between “John Smith” and “age”, and also between “Anytown” and “state”.

To fix this, you would add commas as follows:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }
}

By adding commas between each item except for the last one, the JSON object is now in the correct format and should parse without error.

3. Make sure to use double quotes and escape special characters.

JSON strings must be wrapped in double quotes, and any special characters within the string must be properly escaped. Consider the following example:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    },
    "message": "It's a lovely day"
}

When we try to parse this with JSON.parse, we will get the error: SyntaxError: Invalid or unexpected token.

The problem is with the following line using a apostrophe:

"message": "It's a lovely day"

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    },
    "message": "It's a lovely day"
}

As we can see, this will fix our error since we escape the aspostrophe as such:

"message": "It's a lovely day"

4. Check for mismatched brackets or quotes.

Make sure all brackets and quotes are properly closed and match up.

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }

In this example, the JSON object is missing a closing curly bracket, which indicates the end of the object. Because of this, it will throw a “syntaxerror unexpected token” error.

To fix this, you would add the missing closing curly bracket as follows:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }
}

If you want to be sure that the JSON is valid, we can try to use the NPM package JSONLint (https://github.com/zaach/jsonlint)

We can install jsonlint with npm as follows:

  1. Open up the terminal
  2. Run NPM install npm install jsonlint -g
  3. We can then validate a file like so: jsonlint myfile.json

Summary

In this article I went over the SyntaxError: Unexpected token < in JSON at position 0 when dealing with parsing JSON with fetch or JSON.parse. This error is mainly due to the JSON not being in correct format or the content that we are trying to parse is not even JSON.

In the case of JSON being invalid, make sure to check for unescaped characters, missing commas, non-matching brackets and quotes.

To be really sure, check the JSON with tools like JSONLint to validate!

In the case of the content you are trying to parse being non-JSON such as HTML, check your API to make sure that error pages return JSON correctly instead of HTML pages.

I am trying to implement user registration in my app. I used node.js express to create my backend and passed a insert query in a .js file i created in the router folder. I have added all the necessary things in app.js too.

Following is my backend code.

var express = require('express');
var router = express.Router();
var mysql =  require('mysql');

var connection = mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: '',
      database:'MobileDB',
})

/* GET users listing. */
router.post('/', function(req, res, next) {

        var name = req.body.name;
        var email = req.body.username;
        var password = req.body.password;
        var phone = req.body.phone;
        connection.query("INSERT INTO `user` (`id`, `name`, `username`, `password`, `phone`) VALUES (NULL, '', '', '', '')",[null,name,username,password,phone],function(err,row,fields){
          if (err) console.log(err);

          if(row.length > 0){
              res.send({'success': true, 'message': 'welcome new user'});
          } else {
            res.send({'success':false,'message':'user not found, please try again'});
          }
      });
  });

module.exports = router;

and The following is my registration page:

import React, { Component } from 'react';
import{
  Image,
  View
} from 'react-native';
import { Container, Content, List,Thumbnail, ListItem, InputGroup, Input, Icon, Text, Picker, Button,Header,Footer} from 'native-base';
import {
Router,
Actions,
Scene } from 'react-native-router-flux';
const Item = Picker.Item;
export default class Reg extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name:'',
            username:'',
            password:'',
            phone:'',
            }

        };
    }
      Reg = () => {

            fetch('http://192.168.0.20:3000/reg', {
             method : 'POST',
                  headers: {
                  'Accept': 'application/json',
                  'Content-type': 'application/json',
                  },

                  body: JSON.stringify({
                  name:this.state.name,
                  username:this.state.username,
                  password:this.state.password,
                  phone:this.state.phone,

                  })
            })

            .then((response) => response.json())
            .then((res) => {
                  if(res.success=== true){
                  var username = res.message;

                     AsyncStorage.setItem('username', username);
                     Actions.Ideas();}
                     else {
                    alert(res.message);
                }

            })

            .done();

      }
    render(){
      return(
      <Container>
            <Content>
                    <View style={{alignSelf:'center'}}>
                    <Button transparent onPress={Actions.upload}>
                    <Icon name='ios-contact' style={{fontSize:30}}/>
                    </Button>
                    </View>
                    <View style={{top:20}}>
                    <List>
                        <ListItem>
                            <InputGroup>
                                <Icon name="ios-person-outline" style={{ color: '#5bc0de' }} />
                                <Input onChangeText={(name) => this.setState({name})}
                                  value={this.state.name} placeholder="Name" />
                            </InputGroup>
                        </ListItem>
                        <ListItem>
                            <InputGroup>
                                <Icon name="ios-at-outline" style={{color:'#5bc0de'}}/>
                                <Input onChangeText={(username) => this.setState({username})}
                                   value={this.state.username} placeholder="Email" />
                            </InputGroup>
                        </ListItem>
                        <ListItem>
                            <InputGroup>
                                <Icon name="ios-lock-outline" style={{ color: '#5bc0de' }} />
                                <Input onChangeText={(password) => this.setState({password})}
                                 value={this.state.password}placeholder="Password" secureTextEntry />
                            </InputGroup>
                        </ListItem>
                        <ListItem>
                            <InputGroup>
                                <Icon name="ios-call-outline" style={{ color: '#5bc0de' }} />
                                <Input onChangeText={(phone) => this.setState({phone})}
                                 value={this.state.phone}placeholder="Phone" keyboardType="numeric" />
                            </InputGroup>
                        </ListItem>

                    </List>
                    <Button info style={{ alignSelf: 'center', marginTop:20, marginBottom: 20 }} onPress={this.Reg}>
                        SIGN UP
                    </Button>
                    </View>
                </Content>
            </Container>

        );
    }
}

When i click on the SignUp button it shows unrecognised token error. I can’t figure out where i went wrong. Please help.


Attach Chrome debugger and enable pause on exceptions, you will get to know what is going wrong.

This guide will help you to fix SyntaxError: Unexpected token < in JSON at position 0. This guide also applies to these other common variants of the same error:

  • SyntaxError: The string did not match the expected pattern.

  • SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

  • JSON parse error: Unrecognised token '<'

Summary

These errors indicate that your JavaScript code expected to receive JSON but got something else instead (probably HTML in the form of a server-side error). To fix the issue, you need to examine what you got instead of the expected JSON to determine what the problem is.

Details

Usually, this error is caused when your server returns HTML (which typically begins with <DOCTYPE html> or <html>) instead of JSON. Valid JSON cannot begin with a < character, so the JSON parser knows immediately that the data isn’t valid JSON and produces one of the error messages mentioned above.

To fix this error, you need to figure out why you’re getting HTML (or something else) instead of the JSON you expected. To do this, you need to log the data that you’re trying to parse to the console.

If you’re using fetch()

Use this approach if your code looks something like this:

fetch('https://example.com/some/path/to/json')
.then(function (response) {
    return response.json();
})
.then(function (data) {
    // Do something with data
});

In this case, the error is thrown when response.json() tries to run and fails to parse the data from the server as JSON. You can add a function to handle the error, display the raw text of the response body from the server and log it to the console (see notes about commented lines below):

var responseClone; // 1
fetch('https://example.com/some/path/to/json')
.then(function (response) {
    responseClone = response.clone(); // 2
    return response.json();
})
.then(function (data) {
    // Do something with data
}, function (rejectionReason) { // 3
    console.log('Error parsing JSON from response:', rejectionReason, responseClone); // 4
    responseClone.text() // 5
    .then(function (bodyText) {
        console.log('Received the following instead of valid JSON:', bodyText); // 6
    });
});

Here’s an explanation of each line with a numbered comment:

  1. responseClone variable is required to hold a clone of the response object because the body of a response can only be read once. When response.json() is called, the body of the original response is read, which means it cannot be read again while handling the JSON parse error. Cloning the response to responseClone provides two copies of the response body to work with; one in the original response to use with response.json() and another to use with responseClone.text() if response.json() fails.

  2. This line populates the responseClone variable with a clone of the response received from the server.

  3. A second function argument is passed to the then() function that follows the response.json() call. This second function will be called if the promise from response.json() is rejected (i.e. a JSON error is encountered).

  4. This line logs the rejectionReason from the rejected response.json() promise and the responseClone so it can be examined if needed (the HTTP status code is often useful for debugging, for example).

  5. Instead of trying to parse the response body from the server as JSON, it is processed as raw text.

  6. The body text is logged to the console for examination.

If you’re using JSON.parse()

Use this method if the code that’s throwing the error looks like this:

JSON.parse(data);

In this case, you can log the data to the console if an error is encountered to see what it contains:

try {
    JSON.parse(data);
}
catch (error) {
    console.log('Error parsing JSON:', error, data);
}

What do I do next?

Once you can see the data that’s causing the JSON parse error, it will hopefully provide a clue as to why you’re not getting the valid JSON you expect. Some of the most common issues that lead to this error are:

  • If you see HTML indicating a 404 Not Found error instead of the JSON you expect, check the URL you’re passing to fetch() and make sure that it’s correct.

  • If you see HTML indicating a server error (such as a 500 error code), examine your server’s error logs to determine why your server is encountering an error instead of providing the JSON you expect.

  • If you cannot see anything or if you have an unusual jumble of characters, check your variable assignments and character encodings.

Понравилась статья? Поделить с друзьями:
  • System error 001 details success
  • Syntaxerror invalid syntax python как исправить
  • Syntaxerror illegal character line nan error code 991
  • System error 001 details failure contact the bank 1с
  • Syntaxerror eol while scanning string literal как исправить