-1

Problem: I am sending a get request to node using the fetch API, but I am getting the following error

Read comment in code

Sends get request to sever

server.js

const express = require('express');

const app = express();
const bodyParser = require('body-parser');

const notes = [
    {id: 0, title: "Dinner", body: "- Chicken - Rice - Potatos"},
    {id: 1, title: "Dinner", body: "- Chicken - Rice - Potatos"}
];

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res, next)=>{
    // Sending data!
    res.json(notes);
})

const port = 3001;

app.listen(port, ()=> console.log(`Server started on port ${port}`));

app.js

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

  componentDidMount(){
    // Line where I get the error
    fetch('/')
      .then(resp => resp.json())
      .then(data => this.setState({notes: data}))
  };
M Masood
  • 167
  • 1
  • 10
  • 1
    Put a `.catch()` handler at the end of your `fetch()` promise chain and log the exact error it reports. You should always have a `.catch()` handler anyways. – jfriend00 Oct 26 '19 at 07:19

2 Answers2

1

The error suggests that the parsed string is not a JSON. Since we don't see the full setup of the client my guess would be that you are not requesting the dev server and that's why you get the error.

To check this try:

fetch('/').then(res => res.text()).then(text => console.log(text))

This will output the response as plain text and you will see if you are requesting the correct URL and getting the JSON you expect. If you don't, just use the absolute URL (localhost or 127.0.0.1 or whatever you configured for the server) with the 3001 port.

Goran Stoyanov
  • 2,311
  • 1
  • 21
  • 31
0

server.js shows that it has only one endpoint: /

This means that your React app must be served from a different HTTP server.

You said fetch('/'), which is a relative URL, so you are requesting / from the server hosting the React app and not the server created by server.js

This means you are probably fetching the HTML document which bootstraps the React application. This tracks with the error message which says the file at / starts with a <.

You need to request the data from the server that actually hosts it:

`fetch('http://localhost:3001/')`

However, this will be a cross-origin request, so you also need to have server.js give permission to the browser to expose the JS to the JavaScript from the React application. Since you are using Express, you can do this with the cors module.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • That is not the issue, in my package.json file I have set proxy `"proxy": "http://localhost:3001"`, which reads this fetch('/') as fetch('http://localhost:3001/'). This means typing less – M Masood Oct 26 '19 at 13:24
  • @MMasood — It is the issue. `proxy` will only proxy **unknown** URLs. `/` isn't unknown. It is the HTML document that bootstraps the React application. – Quentin Oct 26 '19 at 14:52