Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Express disable CORS by default?

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!

like image 891
judgejab Avatar asked Jan 03 '18 12:01

judgejab


Video Answer


1 Answers

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.

like image 146
Joe Clay Avatar answered Sep 21 '22 16:09

Joe Clay