Cross-domain problems are often encountered when sending requests using a browser, but there are many solutions to these problems. One of the classic approaches is cross-Origin Resource Sharing, where CORS uses the extra HTTP header to count which addresses browsers can make cross-domain Resource requests.
Cause of cross-domain
Cross-domain literally means cross-domain, but it has a deeper meaning. In fact, any difference in protocol, domain name, or port is considered a different domain. If there is no cross-domain, you can reference external files casually, and pages under different tags can reference each other, browsers will be confused, and security will not be guaranteed. Browsers restrict cross-domain HTTP requests for security reasons, known as the same origin policy, so the backend needs to set the request header to allow cross-domain requests.
Cross-domain solution using CORS
The basic idea of CORS is to use custom HTTP headers to let the browser communicate with the server to determine whether a request or response is successful or unsuccessful. Currently, all browsers support this function. Internet Explorer requires Internet Explorer 10 or later. The entire CORS communication process is automatically completed by the browser without user involvement. So developers can easily solve cross-domain problems by simply implementing the CORS interface in the server.
To support CORS on the server, the primary configuration is access-Control-Allow-Origin, which allows cross-domain Access when the browser detects a response setting.
Http.createserver ((req, res) => {// Which clients are allowed to Access res.setheader (' access-Control-allow-origin ', "http://127.0.0.1:5500")Copy the code
After configuring this code on the server side, we were able to allow cross-domain access to the local 5500 port. Of course, we can secure cross-domain communication with more detailed configuration. As follows:
const http = require('http') http.createServer((req, Res.setheader (' access-Control-allow-origin ', "http://127.0.0.1:5500") Res. setHeader(' access-Control-allow-headers') "Token, XXX ") // allows those Methods to Access res.setheader (' access-Control-allow-methods ', "OPTIONS") // Can every half hour, To send an option request res.setheader (' access-Control-max-age ', '1800') if(req.method ==="options"){ return res.end() } if (req.url == "/api") { res.end(JSON.stringify({ name: 'wangcai' })) } }).listen(3000)Copy the code
You can perform the corresponding configuration on the HTML page
<script>
fetch("http://localhost:3000/api", {
method: 'GET'.headers: {token:'xxx'
}
}).then(res= > {
return res.json()
}).then(json= > {
console.log(json)
})
</script>
Copy the code
A brief summary of CORS. In the early stage, JSONP is generally used to solve the problem. However, JSONP has great limitations and can only achieve GET requests. In contrast, COSR has greater flexibility. Has become the mainstream method to solve cross-domain, above…