网站跨域问题

网站报错

当发生跨域问题时,会出现如下错误:

1
Access to XMLHttpRequest at 'http://192.168.1.100:8123/portal/notice/updateAnnexInfo' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

报错原因

网站和其他源的资源的交互式被同源策略保护的,而对于两个URL的protocol、port和host都相同,则这两个URL是同源,否则不是同源,会被同源策略保护而报上面的错误。

解决方法

Vue项目

开发环境跨域解决

如果要在生产环境中解决跨域问题,需要在Vue.config.js中进行如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
devServer: {
proxy: {
// 配置跨域
'/api': {
target: 'http://192.168.1.100:8123/portal',
ws: true,
changOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
},

生产环境跨域解决

该配置需要在服务器上解决,我用的是nginx服务器,因此只有nginx服务器的解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80; #监听端口

location / {
root html;#文件根目录
index index.html index.htm;#默认起始页
}

location /api {
proxy_pass http://192.168.1.100:8123/portal; //配置代理的路径
}
}

上面是最基础的服务器跨域设置,该配置其实就是使用nginx进行了代理配置。