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?

2 Answers 2

2

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",

Sign up to request clarification or add additional context in comments.

1 Comment

this way: ` fetch('localhost:3000/items')` . items without the .json extension
1

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

1 Comment

Weird...the response is supposed to be straight json...but html does explain the 404. so yes, have to trap at that place first. thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.