跨域资源共享(CORS) 是一种机制,它使用额外的 HTTP 头来告诉浏览器 让运行在一个 origin (domain) 上的Web应用被准许访问来自不同源服务器上的指定的资源。
当一个资源从与该资源本身所在的服务器不同的域、协议或端口请求一个资源时,资源会发起一个跨域 HTTP 请求。
开发环境
在 Vue 中,可以在 config/index.js 中配置代理。
dev: {
proxyTable: {
'/api/v1': {
// 接口域名(后台接口地址)
target: 'http://10.***.**.**:****',
// 如果是https接口,需要配置这个参数
secure: false,
//代理websocket
// ws:true,
//是否跨域
changeOrigin: true,
pathRewrite: {
//需要rewrite的, 将 /api/v1 替换为 /api/v1
'^/api/v1': '/api/v1'
}
}
}
}
生产环境
生产环境下就不能用 webpack 自带的代理去处理跨域问题了。只能在服务端去做操作了。
我这里使用的是 Nginx 解决的跨域问题。
- 首先下载 Nginx 官网
- 然后找到 Nginx 的配置文件
conf/nginx.conf - 配置代理,如下所示
server {
# nginx服务项目端口
listen 8088;
# nginx服务IP 些自己本地IP就行
server_name 10.219.**.**;
#charset koi8-r;
#access_log logs/host.access.log main;
# 监听地址关键字
location /api/v1 {
# 跨域相关
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
# 转换成需要的代理地址(后端接口地址)
proxy_pass http://10.219.88.61:8889/api/v1;
}
}