ColdSharper ColdSharper - 8 months ago 187
JSON Question

React App not resolving fetch route: Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0

My fetch source ('wx') in an express server is returning:
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
at the fetch line below. The fetch source of 'wx' returns 404.(Although this is setup for ultimately a weather service, any test here returns 404).

This is the React:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
state = {wx: []}

componentDidMount() {
fetch('/wx').then(res => res.json()).then(wx => this.setState({ wx }));

render() {
return (
<div className="App">
{ =>
<div key={}>{weather.main}>{weather.description}</div>


export default App;

And here is the route wx.js:

var express = require('express');
var app = express();
var router = express.Router();
var request = require('request');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

app.get('/', function(req, res){

url: '', //URL to hit
method: 'POST'

}, function(error, response, body){
if(error) {
} else {


module.exports = router;

Why does this return 404 and what can I do about it?

Answer Source

Your error is related to that 404 error you are receiving. res.json() trying to convert the body of your response to a JSON object and it is failing because response is a HTML document.

What you can do is to check if the response is successful before returning json.

fetch('/wx').then(res => {
  if(res.status === 200) return res.json();
  else return { error: 'there was an error with response' }
}).then(wx => {
  if(wx.error) { /* handle error here */ }
  else {
    this.setState({ wx })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download