I am currently building a back-end server using express.js. It was working fine until I got this problem with the web based version of my project:
Access to XMLHttpRequest at 'myurl.net/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Strangely enough, I can access the back-end server from the app version written with Kotlin without any problems and make POST, GET requests. What am I doing wrong now?
In the front-end server I develop with React.JS, the request looks like this: (JavaScript)
axios.post("myurl.net/", {
email: "[email protected]",
password: "mypassword",
newuser: "false"
}).then(function (res) {
console.log(res)
}).catch(function (error) {
console.log(error)
})
The Express Server looks like this (I have reduced it to a single request to make it clearer):
require("dotenv").config();
const express = require("express");
const listen = require("./listen")
const bodyParser = require("body-parser");
const service = express();
service.use(bodyParser.urlencoded({ extended: false }));
service.use(bodyParser.json());
service.set("view engine", "ejs")
service.all('/*', function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "false");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
next();
});
service.post("/", async (req, res) => {
if(req.body.test == "hello_world") {
res.json({
server: "hello"
})
}
})
listen(service)
By the way, locally the back-end server works strangely, on the server with a domain and HTTPS then somehow not.
CodePudding user response:
Pay close attention to the error message:
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Then look up preflight request:
It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method, Access-Control-Request-Headers, and the Origin header.
You don't have a handler for service.options("/"
so it 404s.
You need to respond with a 200 OK status.
I strongly recommend the use of the cors
middleware package which will take care of this for you.