跨域指浏览器不允许当前页面的所在的源去请求另一个源的数据。 源指协议,端口,域名。只要这个3个中有一个不同就是跨域。
列子: #协议跨域 http://a.abc.com访问https://a.abc.com; #端口跨域 http://a.abc.com:8080访问http://a.abc.com:80; #域名跨域 http://a.abc.com访问http://b.abc.com;
在 vue.config.js 中配置devServer
module.exports = { publicPath: '/', outputDir: 'dist', assetsDir: 'assets', // 静态资源目录 (js, css, img, fonts) lintOnSave: process.env.NODE_ENV !== 'production', devServer: { //跨域 port: "8080", //端口号 host: "localhost", open: true, //配置自动启动浏览器 proxy: { // 配置跨域处理 可以设置多个 '/api': { target: 'http://a.abc.com:8081',//跨域请求头信息 changeOrigin: true, ws: false, secure: false, // 如果是https接口,需要配置这个参数 pathRewrite: { '^/api': '/' } //pathRewrite: {'^/api': '/'} 重写之后url为 http://a.abc.com:8081/xxxx //pathRewrite: {'^/api': '/api'} 重写之后url为 http://a.abc.com:8081/api/xxxx } } }发送请求:
axiosF(){ this.$axios.get("api/v2") .then(res=>{ console.log(res) }).catch(err=>{ console.log(err) }) }请求http://localhost:8080/api/v2就会被代理到http://a.abc.com:8081/v2 注意请求后必须添加api否认不会被代理。可以设置 axios 的 baseURL 值 axios.defaults.baseURL = ‘/api’ 这样会为所有的 请求url 前面都加上 ‘/api’,方便做 统一代理。
axiosF(){ this.$axios.get("/v2") .then(res=>{ console.log(res) }).catch(err=>{ console.log(err) }) }nginx.conf文件配置 server { listen 80; server_name a.abc.com; location / { # 这里是根目录的项目 try_files $uri $uri/ /index.html; root /home/html/travel/dist; index index.html index.htm; } # 这里是需要部署的二级目录应用配置 location ^~/api/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://a.abc.com:8081; } }
