当前位置:首页 > 开发教程 > js/jQuery教程 >

vuecli3打包后出现跨域问题,前端配置拦截器无效的解决

时间:2022-06-02 17:32 来源:未知 作者:等迩宛在水中央 收藏

这篇文章主要介绍了vuecli3打包后出现跨域问题,前端配置拦截器无效的解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

打包后跨域问题,前端配置拦截器无效

问题

这几天在把项目弄好,打包完成后发现之前cli配置的拦截器没有在打包后没起到作用,使用别的方法通过nginx反向代理进行配置跨域。

解决方案

在nginx里面的nginx.config里面配置

配置如下

server {
        listen       80;#监听端口
        server_name  localhost;#代理服务地址
        add_header Access-Control-Allow-Origin *;
        location / {
            root C:/nginx-1.19.0/html/dist; #根目录!!,把这里路径设置为项目的根路径
            autoindex on;       #开启nginx目录浏览功能
            autoindex_exact_size off;   #文件大小从KB开始显示
            charset utf-8;          #显示中文
            add_header 'Access-Control-Allow-Origin' '*'; #允许来自所有的访问地址
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS'; #支持请求方式
            add_header 'Access-Control-Allow-Headers' 'Content-Type,*';
        }
        #开始配置我们的反向代理
        location /apis{//cli配置的接口名
           rewrite ^/apis/(.*)$ /$1 break;
           include uwsgi_params;
           proxy_set_header   Host             $host;
           proxy_set_header   x-forwarded-for  $remote_addr;
           proxy_set_header   X-Real-IP        $remote_addr;
           proxy_pass  http://*****:8080;//接口
        }
        
          location /topicByCate{//cli配置的接口名
           rewrite ^/topicByCate/(.*)$ /$1 break;
           include uwsgi_params;
           proxy_set_header   Host             $host;
           proxy_set_header   x-forwarded-for  $remote_addr;
           proxy_set_header   X-Real-IP        $remote_addr;
           proxy_pass  https://******.com;//接口
        }
        location @router {
            rewrite ^.*$ /index.html last;
        }
    }

vue3处理跨域问题

在项目根目录新建vue.config.js输入

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://www.example.com:81/', //接口域名,端口看各自设置的
        changeOrigin: true,       //是否跨域
        ws: true,            //是否代理 websockets
        secure: true,          //是否https接口
        pathRewrite: {         //路径重置
          '^/api': ''
        }
      }
    }
  }
};

如用到的是vite.config.js

则在这个文件添加

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://www.example.com:81', //接口域名,端口看各自设置的
        changeOrigin: true,       //是否跨域
        ws: true,            //是否代理 websockets
        secure: true,          //是否https接口
        pathRewrite: {         //路径重置
          '^/api': ''
        }
      }
    }
  }
};

以上为个人经验,希望能给大家一个参考,也希望大家多多支持源码搜藏网。


下一篇:没有了

js/jQuery教程阅读排行

最新文章