I use the follow first middleware.Due to the token header, the first request to the server is OPTIONS request.For some reason, after reload both the client and server sides, SOMETIMES non-deterministically the request can reach to 'console.log("C")' and send status 200.
app.use(function(req, res, next) {
console.log("A")
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");
res.header('Access-Control-Max-Age', String(60 * 60 * 24 * 365));
console.log("B")
if(req.method === 'OPTIONS'){
console.log("C")
res.sendStatus(200);
return res;
}
console.log("D")
next();
});
But subsequent GET or POST requests don't pass because of the message:
...has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
But if to use curl:
curl -I -X OPTIONS http://127.0.0.1:3003/handler
I always get a normal response, which shows all the necessary headers for CORS
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, token
Access-Control-Max-Age: 31536000
Content-Type: text/plain; charset=utf-8
Content-Length: 2
ETag: W/"2-nOO9QiTIwXgNtWtBJezz8kv3SLc"
Date: Sat, 28 Mar 2020 07:24:18 GMT
Connection: keep-alive
With GET, POST requests in a similar way, everything is fine through the curl. But through the browser (using axios) it does not work. Again, it sounds crazy, but sometimes I correct / reload something, the request may even be successful, but when I pull the next handler, for example, / handler2, everything falls again.
Client:
axios.defaults.baseURL = "http://127.0.0.1:3003";
axios.defaults.headers.common["token"] = window.localStorage.token;
window.axios = axios;
axios.post("/user/handler", postData).then(...).catch(...);
Please, don't say about app.use(cors()) or app.options(...) ))
I'm sitting on it already God knows how much... tried everything possible. But I think the problem because of the client, but not the server...In the end, for curl it works.