Home > Net >  How to Configure Server API to Receive a Request Body Using Fetch and Express JS?
How to Configure Server API to Receive a Request Body Using Fetch and Express JS?

Time:04-10

I'm trying to send a JSON file from the client to the server, but when I try to do so I get the error: "No 'Access-Control-Allow-Origin' header is present on the requested resource". I also get the errors "POST http://localhost:3000/ net::ERR_FAILED" and "Uncaught (in promise) TypeError: Failed to fetch at index.js:6:1", but I'm not sure if they're relevant or symptomatic of the first error. I'm using localhost:8000 to run my front end.

Client

let data = 
{
    'subject': 'test'
}

fetch('http://localhost:3000',
{
    method : 'POST',
    headers: {'Content-Type' : 'application/json'},
    body : JSON.stringify(data)
})
.then(response => response.json()).then(data => console.log(data));

Server

const express = require('express');
const app = express();
app.use(express.json());

const port = 3000;

app.post('/', (req, res) => 
{
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
    console.log("Success");
});

app.listen(port);

I'm new to the concepts involved in connecting the front and back ends of a website, but I wanted to learn how for a project. I started by following a tutorial suggesting to set the response header "Access-Control-Allow-Origin : http://localhost:8000" to the response on the server side, which worked great for GET requests. But when I tried to do the same with a POST request, I started getting the error.

When I send the POST request without headers or a body, it works fine and I'm able to even receive a response without the error. I've also tried adding the "Access-Control-Allow-Headers : Content-Type" and "Content-Type : application/json" headers to the request on the server with the "Access-Control-Allow-Origin" header, but to the same problem.

I've attached the full error in case it'll be helpful. I'm new to posting in help forums, so if there's any more information needed or a better way to write or post my questions in the future, please let me know; I'd like to fix it. Thank you!

Errors Image

CodePudding user response:

Your client is running on localhost port 8000, while your backend is running on localhost port 3000, which is causing a Cross Origin Resource Sharing (CORS) problem.

Basically, Javascript running on an application can only talk to a server from the same origin by default.

An easy way to fix this is to use the Node cors middleware.

Run npm i cors

Then in your server:

const cors = require('cors');
app.use(cors());

This should allow requests from other origins.

EDIT: Researched your problem a little more and it looks the reason your original code wasn't working was because the server isn't responding to the pre-flight request. I was able to get your code working on my machine following this answer on SO.

This is what the server looks like now:

const express = require('express');
const app = express();
app.use(express.json());

const port = 3000;

app.options('/', (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  res.end();
});

app.post('/', (req, res) => 
{
    console.log("Success");
});

app.listen(port);
  • Related