Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "same-origin" and "no-cors" for JavaScript's Fetch API?

I thought same origin implies no CORS, and vice-versa. What's the difference between the two options for JavaScript's Fetch API's mode option?

Also, in the specs, it says:

Even though the default request mode is "no-cors", standards are highly discouraged from using it for new features. It is rather unsafe.

Why is it unsafe? Source: https://fetch.spec.whatwg.org/#requests

like image 211
Leo Jiang Avatar asked Mar 10 '16 08:03

Leo Jiang


People also ask

What does no-CORS mean in Fetch?

no-cors. Prevents the method from being anything other than HEAD , GET or POST , and the headers from being anything other than simple headers. If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers.

What is mode CORS in Fetch?

mode. The mode option is a safe-guard that prevents occasional cross-origin requests: "cors" – the default, cross-origin requests are allowed, as described in Fetch: Cross-Origin Requests, "same-origin" – cross-origin requests are forbidden, "no-cors" – only safe cross-origin requests are allowed.


1 Answers

With same-origin you can perform requests only to your origin, otherwise the request will result in an error.

With no-cors, you can perform requests to other origins, even if they don't set the required CORS headers, but you'll get an opaque response.

You can read more on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Request/mode and https://developer.mozilla.org/en-US/docs/Web/API/Response/type.

like image 57
Marco Castelluccio Avatar answered Sep 28 '22 03:09

Marco Castelluccio