John White
John White

Reputation: 131

Express route /index.js not working in my React app

I'm trying to fetch a json object in my React app from index.js in Express, but when it loads I get "Unhandled Rejection (SyntaxError): Unexpected token P in JSON at position 0".

I fetched successfully when I used /users.js as the route.

(index.js)

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

 router.get('/', function(req, res, next) {
   vitamins: [
     {
        name: "Vitamin B2"
     }
   ],
   minerals: [
     {
        name: "Zinc"
     }
   ]});
 });


 (React app)

  componentDidMount() {
   fetch('/index')
     .then(res => res.json())
     .then(micros => {
     this.setState({
       micros: micros.vitamins
     });
   })
  }

Again, it worked fine when I fetched from /users.js using the same code. Instead I just did fetch('/users'). I also tried just doing fetch('/'), but I just get "Unexpected token < in JSON at position 0".

Upvotes: 0

Views: 204

Answers (2)

Colin Ricardo
Colin Ricardo

Reputation: 17239

I think you need to do:

fetch('/')

not

fetch('/index')

in your React code.

Upvotes: 0

The error, Unexpected token < in JSON at position 0 is coming due to the fact that your response is not really a json but a HTML, something like a 404 html response or a 500 response. It is recommended to not make a direct server call with '/'. This is mainly for loading the entire application which usually returns an HTML. You should maintain separate mapping for end points like you mentioned 'users' and then call it from React fetch. Put some additional console logs or debug when you first get the response and you will be able to figure out the actual response that is being returned by server

Upvotes: 1

Related Questions