wallwalker
wallwalker

Reputation: 621

Why do I get error net::ERR_CONNECTION_REFUSED with JSON Server POST request?

Resolution : See Hassan Imam's comment below.

I've got a React project running on http://localhost:3000/ and my JSON server on http://localhost:5000/tasks.

I can DELETE a task from the server (data on db.json gets deleted) without errors however I'm getting CORS errors in chrome & firefox when I attempt to add a task with POST method.

I run into the CORS issues below :

Chrome :

POST http://localhost/5000/tasks net::ERR_CONNECTION_REFUSED

Firefox :

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/5000/tasks. (Reason: CORS request did not succeed).

Starting server with :

npm run server

App.js :

const addTask = async (task) => {
    const res = await fetch('http://localhost/5000/tasks', {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify(task),
    });

    const data = await res.json();

    setTasks([...tasks, data]);
    
  };

package.json

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "server": "json-server --watch db.json --port 5000"
  },

I've attempted to add 'Access-Control-Allow-Origin': '*', to the header but still getting the same errors.

Anyone have thoughts? Am I supposed to add something to the headers in fetch or somehow configure the JSON server via the command line?

Upvotes: 0

Views: 9791

Answers (1)

nishit chittora
nishit chittora

Reputation: 1034

Chrome browser blocks Cross-origin requests. And in turn hits OPTIONS requests which are also known as pre-flight requests in Cross-origin resource sharing (CORS).

This pre-flight request is made by chrome browser as a safety measure to ensure that the request being done is trusted by the server. Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon.

There are different way you can handle this by adding --no-cors read more here

"server": "json-server --watch db.json --port 5000 --no-cors"

Upvotes: 2

Related Questions