vuecli3打包跨域配置拦截器无效

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vuecli3打包跨域配置拦截器无效

圆内~搁浅   2022-06-05 我要评论

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

问题

这几天在把项目弄好,打包完成后发现之前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': ''
                }
            }
        }
    }
};

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们