Ошибка unexpected token doctype is not valid json

Getting SyntaxError: Unexpected token < in JSON at position 0 when using fetch or JSON.parse. I will go over fixes for this!

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.

It seems like the server is returning HTML instead of JSON. This is why you’re getting the «Unexpected token ‘<‘» error, because the HTML is not valid JSON.

  • To fix this issue, you need to check what the server is sending back
    and make sure it’s returning a JSON object. If the server is not set
    up correctly, you’ll need to correct that.
  • Additionally, make sure that the API endpoint you’re sending the
    request to is correct and it’s the endpoint that is set up to receive
    and handle POST requests.
  • You can also check the response headers and status code of the
    server’s response to see if there’s any error being returned.

Here’s a working code example for sending data from your React Native app to a backend and display the response data in the console:

import React, {Component} from 'react';
import {View, TouchableOpacity, Text} from 'react-native';

const API_URL = 'http://your-backend-endpoint.com';

class App extends Componenenter code heret {
  constructor(props) {`enter code here`
    super(props);
    this.state = {
      data: {},
    };
  }

  handlePress = () => {
    fetch(API_URL + '/get', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: 'item name',
        description: 'item description',
      }),
    })
      .then(response => response.json())
      .then(responseJson => {
        console.log(responseJson);
        this.setState({
          data: responseJson,
        });
      })
      .catch(error => {
        console.error(error);
      });
  };

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this.handlePress} style={styles.button}>
          <Text style={styles.buttonText}>Send Data</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = {
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    backgroundColor: '#ddd',
    padding: 10,
    borderRadius: 5,
  },
  buttonText: {
    fontSize: 18,
    color: 'black',
  },
};

export default App;

Author: Chukwuka Reuben

Introduction.

This post aims to address the «Unexpected token in JSON at position 0» error message. We will look into the various possible causes of this message and suggest methods to rectify it.

Steps we’ll cover:

  • What is JSON?
  • What does the «Unexpected token < in JSON at position 0» error mean?
  • Different Reasons Why You Might Have This Error and Their Fixes.
  • Hitting Any API endpoint that does not exist:
  • Spelling Error
  • Forgetting to stringify your object:

What is JSON?

JSON which stands for Javascript Object Notation can be said to be a lightweight format for storing and transporting data, it is used often when data is sent from a server to a webpage.

If you have ever utilized API endpoints in your projects before, there’s a very high chance that JSON is being used to store and transport data between your web page and servers.

Let us quickly examine the utilization of JSON for transporting and storing data. We don’t need to look too far since the local storage on our internet browsers can function as servers.

The codeblock below shows how JSON can be used to transport data between local storage and the web page:

localStorage.setItem('list', JSON.stringfy(list))

JSON.parse(localStorage.getItem('list'))

Enter fullscreen mode

Exit fullscreen mode

Now that we are aware of what JSON is and how it can be applied, let us move on to resolving the «Unexpected token in JSON at position 0» error message.

What does the «Unexpected token < in JSON at position 0» error mean?

In very simple language, «Unexpected token < in JSON at position 0» indicates that you are parsing something else that is not JSON as JSON.

To prove my point, I will attempt to reproduce the mistake. Go to your browser console and execute this code snippet:

JSON.parse(undefined)

Enter fullscreen mode

Exit fullscreen mode

The code snippet above will produce this type of error:

json error description

Why? because «undefined» is not JSON but we have tried to parse it as JSON.

There’s something I would like you to note before we proceed:

The actual «Unexpected token in JSON at position 0» message may vary depending on what your server generates, however, the fundamental reason remains the same: you are attempting to parse something that is not JSON as JSON.

Below are some of the different forms in which the error message could be presented:

  • » is not a valid JSON at JSON.parse».

  • Unexpected token ‘<‘, «<!DOCTYPE «… is not valid JSON.

  • Unexpected token ‘o’, «not found!» is not valid JSON.

  • Unexpected token ‘o’, «[object obj… is not valid JSON»

and so on. So going forward I’ll be using the general name «JSON.parse unexpected token» to refer to this error.

Now that we know what the «JSON.parse unexpected token» error means, let us proceed to know the different reasons why you might have this error and also look into ways to fix them.

Different Reasons Why You Might Have This Error and Their Fixes.

In this section of this article, 4 reasons and their fixes will be listed:

Hitting Any API endpoint that does not exist:

This is one of the most common causes of this error, and this tends to occur during the fetch request in javascript.

As you might have already assumed, yes! it occurs when you’re trying to parse an endpoint result that is not JSON as JSON.

In this part of the article, we will consider two brief cases — one to obtain a valid endpoint and show the outcome, and the other to retrieve an endpoint that doesn’t exist so we can reproduce the error message.

Example 1:

In this example, I’ve used the JSON endpoints from https://dummyjson.com/, a place where you can get fake JSON data to use during development.

I’ve picked a valid endpoint from this site and went ahead to call the javascript fetch method on it, check out the code snippet and its result below:

fetch('https://dummyjson.com/products/1')
  .then(res => res.json())
  .then(json => console.log(json))

Enter fullscreen mode

Exit fullscreen mode

Using the code snippet above, I want to clarify that JSON.parse() is being done by res.json() under the hood.

error description

The image above shows that we got a valid JSON response, now let us move to the second example.

Example 2:

fetch("https://dummyjson.com/myProduct/1")
    .then((res) => res.json())
    .then((json) => console.log(json));

Enter fullscreen mode

Exit fullscreen mode

https://dummyjson.com/myProduct/1 that has been used as our API is an endpoint that I made up, so it is not a valid API endpoint and as you know parsing it will be you trying to parse something that isn’t JSON, as it is not a formatted JSON.

error description

How To Fix.

  • Make sure you are using a valid API endpoint:

    To make sure you are using a valid JSON endpoint, use JSONFORMATTER to verify your endpoints before using it.

  • Always use the try-and-catch within your fetch method or function to prevent your app from crashing.

Spelling Error

This is so much similar to hitting the wrong API, only that you might have been pretty sure that the API endpoint exists.

Spelling error tends to happen due to typographical error or maybe you don’t know what the correct spellings are.

Spelling errors do not apply only to API endpoints, they can also occur while attempting to fetch information from your local storage and lead to the «JSON.parse unexpected token» error message showing up.

How To Fix.

  • Check and proofread well before hitting the API.

  • Make sure you verify your API before hitting it. use JSONFORMATTER.

  • Use the try-and-catch method in your function to prevent your app from crashing.


Building a side project?

Meet the headless, React-based solution to build sleek CRUD applications. With refine, you can build complex projects without having advanced frontend skills.

Try refine to rapidly build your next CRUD project, whether it’s an admin panel, dashboard, internal tool or storefront.

refine blog logo


Forgetting to stringify your object:

If we don’t use the JSON.stringify() technique to convert our object into a string before sending it to a server, then we may encounter the error «JSON.parse unexpected token». This raises the question, «why is it necessary to transform our object into a string before sending it to a server?»

When sending data to a web server, the data has to be a string and to convert a javascript object to a string JSON.stringify() does the trick.

We are going to take two quick examples in this section, example 1 will represent the problem and example 2 will be the solution.

Example 1

Note:

Local storage will stand as our servers in this example.

I have a list of todos that I have written on my web page, I wish for them to stay even after I have reloaded my page*,* how do I make that happen?

I have to send those lists as data to my server, and then to retrieve them whenever I reload the page.

localStorage.setItem("list", 
list);

Enter fullscreen mode

Exit fullscreen mode

In the code snippet that I have provided, I have sent my data to the server without converting the object to a string using JSON.stringify(). Let’s take a look at the consequence this will have on our page, below is the code snippet for retrieving the list, and an image of the result:

const getLocalStorage = () => {
  let list = localStorage.getItem("list");
  if (list) {
    return (list = JSON.parse(localStorage.getItem("list")));
  } else {
    return [];
  }
};

Enter fullscreen mode

Exit fullscreen mode

error description

The error indicates that I’m trying to parse an object, and it’s not a valid JSON.

Example 2(The fix):

All we have to do to fix this error is to stringify our list before sending it to the server:

localStorage.setItem("list", 
JSON.stringify(list))

Enter fullscreen mode

Exit fullscreen mode

The code snippet above will fix the error.

In general, it is always a good idea to carefully check your JSON data for any syntax errors before attempting to parse it. This will help to ensure that your code is able to properly handle the JSON data and avoid any errors like the «Unexpected token in JSON at position 0» error.

Hi, I am experiencing the same problem, using Flutter, Firebase hosting and google_maps_flutter dependency.
In localhost I have no problems. The applications starts, show the maps and apply the style correctly. When hosted on firebase it behaves differently throwing the same exception.

Note: This project also uses the localization feature.

the output of flutter doctor -v is this:

    • Flutter version 3.3.3 on channel stable at C:UsersMaurizioSodanofvmdefault
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 18a827f393 (3 days ago), 2022-09-28 10:03:14 -0700
    • Engine revision 5c984c26eb
    • Dart version 2.18.2
    • DevTools version 2.15.0

[√] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at C:UsersMaurizioSodanoAppDataLocalAndroidsdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: C:Program FilesAndroidAndroid Studiojrebinjava
    • Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
    • All Android licenses accepted.

[√] Chrome - develop for the web
    • Chrome at C:Program FilesGoogleChromeApplicationchrome.exe

[√] Android Studio (version 2021.2)
    • Android Studio at C:Program FilesAndroidAndroid Studio
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)

[√] IntelliJ IDEA Community Edition (version 2021.3)
    • IntelliJ at C:Program FilesJetBrainsIntelliJ IDEA Community Edition 2021.3.2
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart

[√] VS Code, 64-bit edition (version 1.71.2)
    • VS Code at C:Program FilesMicrosoft VS Code
    • Flutter extension version 3.48.0

[√] Connected device (2 available)
    • Chrome (web) • chrome • web-javascript • Google Chrome 106.0.5249.91
    • Edge (web)   • edge   • web-javascript • Microsoft Edge 105.0.1343.53
    ! Device emulator-5554 is offline.

[√] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found! 

the reprodicible sample is here https://github.com/MaurizioSodano/flutter_firebase_issue

And the steps to reproduce are written in the Readme.md:

  1. get a google_maps_api_key https://developers.google.com/maps/documentation/javascript/get-api-key
  2. put this key in web/index.html <script src=»https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY»></script>
  3. run the application: flutter run -d chrome
  4. it should run without problem
  5. create a firebase project
  6. enable the firebase hosting
  7. link your code to firebase project : firebase init hosting (remember to use build/web as public directory)
  8. build your flutter code: flutter build web
  9. deploy on your hosting space: firebase hosting:channel:deploy map-style-issue
  10. open the hosting site and enable the developer mode
  11. inspect the error on the web console, you should see this error: Uncaught FormatException: SyntaxError: Unexpected token ‘<‘, «<!DOCTYPE «… is not valid JSON

In a React app component which handles Facebook-like content feeds, I am running into an error:

Feed.js:94 undefined «parsererror» «SyntaxError: Unexpected token < in JSON at position 0

I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn’t seem to be the case here.

More confusingly, I rolled the code back to an earlier, known-working version and I’m still getting the error.

Feed.js:

import React from 'react';

var ThreadForm = React.createClass({
  getInitialState: function () {
    return {author: '', 
            text: '', 
            included: '',
            victim: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author, 
                                text: text, 
                                included: included,
                                victim: victim
                              })
    this.setState({author: '', 
                  text: '', 
                  included: '',
                  victim: ''
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  loadThreadsFromServer: function () {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  getInitialState: function () {
    return {data: []}
  },
  componentDidMount: function () {
    this.loadThreadsFromServer()
    setInterval(this.loadThreadsFromServer, this.props.pollInterval)
  },
  render: function () {
    return (
    <div className="threadsBox">
      <h1>Feed</h1>
      <div>
        <ThreadForm onThreadSubmit={this.handleThreadSubmit} />
      </div>
    </div>
    )
  }
})

module.exports = ThreadsBox

In Chrome developer tools, the error seems to be coming from this function:

 loadThreadsFromServer: function loadThreadsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

with the line console.error(this.props.url, status, err.toString() underlined.

Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.

EDIT:

I’ve checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.

EDIT 2:

It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads.

I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What’s frustrating here is that this was working correctly the last time I worked on it and can’t find what I could have possibly changed to break it.

In a React app component which handles Facebook-like content feeds, I am running into an error:

Feed.js:94 undefined «parsererror» «SyntaxError: Unexpected token < in JSON at position 0

I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn’t seem to be the case here.

More confusingly, I rolled the code back to an earlier, known-working version and I’m still getting the error.

Feed.js:

import React from 'react';

var ThreadForm = React.createClass({
  getInitialState: function () {
    return {author: '', 
            text: '', 
            included: '',
            victim: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author, 
                                text: text, 
                                included: included,
                                victim: victim
                              })
    this.setState({author: '', 
                  text: '', 
                  included: '',
                  victim: ''
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  loadThreadsFromServer: function () {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  getInitialState: function () {
    return {data: []}
  },
  componentDidMount: function () {
    this.loadThreadsFromServer()
    setInterval(this.loadThreadsFromServer, this.props.pollInterval)
  },
  render: function () {
    return (
    <div className="threadsBox">
      <h1>Feed</h1>
      <div>
        <ThreadForm onThreadSubmit={this.handleThreadSubmit} />
      </div>
    </div>
    )
  }
})

module.exports = ThreadsBox

In Chrome developer tools, the error seems to be coming from this function:

 loadThreadsFromServer: function loadThreadsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

with the line console.error(this.props.url, status, err.toString() underlined.

Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.

EDIT:

I’ve checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.

EDIT 2:

It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads.

I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What’s frustrating here is that this was working correctly the last time I worked on it and can’t find what I could have possibly changed to break it.

Понравилась статья? Поделить с друзьями:
  • Ошибка uds на ивеко еврокарго
  • Ошибка unexpected store extension
  • Ошибка uc3 на частотнике
  • Ошибка unexpected store exception windows 10 причина
  • Ошибка uc1 на частотнике