I have been asked to make sure that a new express server that I've set up enforces against Cross Origin Resource Sharing (CORS) unless the request is coming from a particular URL.
I have found the official express CORS middleware here: https://github.com/expressjs/cors
If I wanted to ENABLE CORS for all requests then I just need to add app.use(cors())
.
If I want to only allow specified urls then I can pass them in as so:
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions))
Correct?
What if I wanted to prevent all origins/URLS from accessing resources on my server?
Is this just the default behaviour of Express?
And if I skipped all this above code, then my server would be protected against all requests?
How am I able to use postman for testing server requests if I haven't enabled CORS using the CORS middleware?
Thanks!
If you don't enable the CORS middleware, your server responses will not contain CORS headers, and browsers will fall back to the standard same-origin policy (i.e. only scripts on the same protocol, domain and port can access it).
Note that none of this is enforced on the server side, though - CORS simply provides information to the browser to allow it to make decisions, and there's nothing stopping a browser implementation from simply ignoring the CORS headers or the same-origin policy. For example, HTTP clients like Postman will usually disregard CORS entirely, as it's not relevant to them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With