ColdSharper
ColdSharper

Reputation: 84

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">
        <h1>Weather</h1>
        {this.state.wx.map(weather =>
          <div key={weather.id}>{weather.main}>{weather.description}</div>
        )}
      </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){

        request({
                url: 'http://jsonplaceholder.typicode.com', //URL to hit
                method: 'POST'

            }, function(error, response, body){
                if(error) {
                    console.log(error);
                } else {
                    console.log(body);
                }
            });

            res.send(body);
    }); 

    module.exports = router;

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

Upvotes: 0

Views: 2314

Answers (2)

Chris Mitchell
Chris Mitchell

Reputation: 21

Sounds like you forgot to set your proxy port in your package.json so its returning html. I had the same Issue and I just for got to set my proxy up in my package.json : "proxy": "http://localhost:3001",

Upvotes: 2

bennygenel
bennygenel

Reputation: 24660

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 })
  }
});

Upvotes: 1

Related Questions