一、什么是跨域
跨域指的是:浏览器不能执行其他网站的脚本,从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域。跨域是由浏览器的同源策略造成的,是浏览器施加的安全限制。a页面想获取b页面资源,如果a、b页面的协议、域名、端口、子域名不同,所进行的访问行动都是跨域的。
二、跨域和同源有什么不同
跨域:.跨域名,跨端口,跨协议
同源:同域名,同端口,同协议
三、解决跨域的方式
1.设置响应头方式解决跨域问题
//node解决跨域问题(app文件)
app.all("*",(req,res,next)=>{
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin","*");
//允许的header类型
res.header("Access-Control-Allow-Headers","content-type");
res.header("Access-Control-Allow-Headers","X-Requested-With,accept,origin,content-type,Authorization");
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
res.header("Content-Type","application/json;charset=utf-8");
if (req.method.toLowerCase() == 'options')
res.sendStatus(200); //让options尝试请求快速结束
else
next();
})
2.CORS:让服务器允许不同域的来源访问
使用中间件解决跨域问题
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 8000;
app.use(cors({ origin: 'http://localhost:3000', credentials: true }));
app.get('/', (req, res) => {
res.json({ message: 'Hello World' });
});
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
3.设置代理
proxy:{
'/api':{
//代理地址
target:'http://localhost:8888/',
// 更改目标源头
changeOrigin:true,
//路径重写
pathRewrite:{
'^/api':''
}
}
}
}