Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No CORS needed for mobile apps?

Tags:

When I make web applications, I usually have to add these headers to Express to allow CORS requests.

app.use((req, res, next) => {   res.header('Access-Control-Allow-Origin', '*');   res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');   res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');   next(); }); 

But with React Native mobile apps, I don't have to do that. Why is that so?

like image 617
Avery235 Avatar asked Nov 11 '17 14:11

Avery235


1 Answers

The point of CORS is to prevent web pages loaded at one domain making AJAX requests or HTTP requests that modify data to other domains. The way it works is web browsers are built to send pre-flight HTTP OPTIONs requests before any such cross-site requests, & the server will send back a message with the Access-Control-* headers designating its CORS policy, & the browser will proceed or abort the request based on what it's told it can do. Since a native app is not a web page loaded from any domain at all, CORS restrictions are not needed or applied, the app's HTTP functions never send an OPTIONS pre-flight, & the server serves the request without CORS ever entering into it. The same is true if you were to try these requests in Postman. Note, however, that if you were to use a hybrid mobile app (Cordova/Ionic/Phonegap, etc.), you would have to deal with CORS, since these apps run in the device's WebView, which is a type of browser & will send pre-flight OPTIONS requests.

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

like image 184
Henry Clayton Avatar answered Sep 19 '22 01:09

Henry Clayton