I was under the impression that cross-origin requests getting blocked was primarily a security thing that prevents evil websites from getting or updating information on your web service.
I've noticed however that even though a request gets blocked on my front-end, the code still executes in the backend.
For example:
import express = require('express')
const app = express()
const port = 80
app.use(function (req, res, next) {
// res.header("Access-Control-Allow-Origin", "*")
// res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
});
app.get('/foo', (req, res) => {
console.log("test1")
res.json({
data: "Hello"
})
console.log("test2")
})
app.listen(port, () => {
console.log(`app listening at http://localhost:${port}`)
})
If my frontend then makes a request the express service, the request will fail because of cross-origin
but the express service will still log
test1
test2
Should express block the service from continuing to run since the origin is not permitted? Isn't a security threat if the express code still executes even if the front-end gets an error?
CodePudding user response:
There are two types of CORs requests in the browser implementation and which is used depends on the specific request being made.
For requests that do not require pre-flight, the request is made to the back-end and then the browser examines the resulting headers to see if the CORs request is permitted or not. If it's not permitted (as in the case you show), then the result of the request is blocked from the client so it can't see the result of the request (even though the server fully processed it).
As best I can tell from what you show, everything here is working as expected. The request is considered a "simple request" and does not require preflight. Browser-based Javascript will not be allowed to get results from this route if it's not the same origin.
For requests that do require preflight (there's a list of things in a request that can trigger preflight), then the browser will first ask the server if the request is permitted by sending an OPTIONS request to the same route. The server then decides whether to allow the request or not. If the browser gets permission from the server, then it sends the real request.
You can see what triggers preflight here.
Presumably, the browser doesn't use preflight all the time because it's less efficient (requiring double the requests).