CORS (Cross-Origin Resource Sharing) :跨域资源共享,CORS是官方的跨域解决方案,完全交给后端进行处理,支持get,post请求。跨域资源共享标准新增了一组 HTTP 首部字段(响应头),允许服务器声明哪些源站通过浏览器有权限访问哪些资源
CORS怎么工作;CORS通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应后会对响应放行
代码实现
客户端
<script>
(function(){
const xhr = new XMLHttpRequest()
xhr.open('GET','http://localhost:3000/cors')
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState ==4){
if(xhr.status>=200&&xhr.status<300){
console.log(xhr.response);
}
}
}
})()
</script>
服务器端
app.use('/cors',(req,res)=>{
Headers:
// Access-Control-Allow-Origin:'*'
// cors 设置响应头 *代表所有请求
res.setHeader('Access-Control-Allow-Origin','*')
// 127.0.0.1:5500 指定这个端口的请求才能被响应
// res.setHeader('Access-Control-Allow-Origin','http://127.0.0.1:5500')
res.send('hello CORS')
})