-1

I established 2 servers: the first one is for frontend (localhost:7200), the second one is for backend (localhost:7300). And there is a test request made by frontend to backend, correspondingly, on a route '/test'.

The problem is when I send a json object (when 'btn' button is clicked) it rejects with the following message:

Access to XMLHttpRequest at 'http://localhost:7300/test' from origin 'http://localhost:7200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Of course, I set 'Access-Control-Allow-Origin' header on backend (see below).

This happens if I set 'Content-Type' header as 'application/json'. But it works fine if there is no header set at all or the header is 'application/x-www-form-urlencoded' (and, therefore, the message sent is not JSON-like).

The code on frontend

btn.addEventListener('click', () => {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://localhost:7300/test', true);
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.addEventListener('load', (e) => {
      console.log(e.target.responseText);
    });

    xhr.send(JSON.stringify({name: 'kek'}))
});

The code on backend:

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

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

app.post('/test', (req, res) => {
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Headers', 'Content-Type')
  // res.set('Content-Type', 'application/json');
  res.header("Content-Type",'application/json');
  console.log(req.body)
  res.json({success: true});
});
SkyFlame
  • 35
  • 5

2 Answers2

1

You can use the cors middleware. https://expressjs.com/en/resources/middleware/cors.html

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

This middleware automatically set headers to avoid CORS issues (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).

spasfonx
  • 170
  • 7
  • Thank you. I marked another answer as the solution, but this article helped me too. I voted your answer up – SkyFlame Feb 27 '19 at 11:43
1

You are setting the headers when your server responds to a POST request.

app.post('/test', (req, res) => {
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Headers', 'Content-Type')

The error message says:

Response to preflight request doesn't pass access control check

The preflight request is an OPTIONS request, not a POST request, so the headers are not set in the response to it and the POST request is never made.


Use the standard cors middleware library. Don't reinvent the wheel.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335