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});
});