📜  no cors (1)

📅  最后修改于: 2023-12-03 15:03:11.616000             🧑  作者: Mango

No CORS

CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers to restrict access to resources from different origins (domains). It prevents untrusted websites from making malicious requests to resources on trusted websites. However, sometimes it may be necessary to allow cross-origin requests for certain use cases. In such cases, the website may opt-out of CORS restrictions by setting the no-cors mode for a fetch request.

What is no-cors Mode?

The no-cors mode is a fetch mode that allows the browser to make cross-origin requests without involving CORS. When a fetch request is made in no-cors mode, the response is restricted to only a few properties, such as status, statusText, and type. Also, the response body is not accessible. This means that if you receive a response in no-cors mode, you can only check if the request was successful (by checking the status property), but you cannot access the response data.

Why Use no-cors Mode?

There are certain use cases where you may want to access resources from a different origin, but you don't need to access the entire response body. For example, if you're building a web app that needs to fetch weather data from a weather API, you may only need the current temperature, not the entire weather forecast. In such cases, you can use no-cors mode to bypass CORS restrictions and fetch the data. Another use case is when you need to make a GET request to a server that doesn't support CORS.

How to Use no-cors Mode?

To use no-cors mode, you need to set the mode property of the fetch request to no-cors. Here's an example:

fetch('https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=YOUR_API_KEY', {
  mode: 'no-cors'
})
  .then(response => console.log(response.status))
  .catch(error => console.error(error))

In the example above, we're making a fetch request to the OpenWeather API to get the current weather for London. We're setting the mode property to no-cors to bypass CORS restrictions. When the response is received, we're logging the response status to the console.

Conclusion

In conclusion, no-cors mode is a fetch mode that allows the browser to make cross-origin requests without involving CORS. It is useful when you don't need to access the entire response body and want to bypass CORS restrictions. However, you should use it with caution, as it can expose your website to security risks. Always make sure you trust the third-party API you're fetching data from and validate the response before using it.