proxy代理不生效、vue config.js不生效解决方法

vue config.js 配置跨域不生效

axios默认请求接口就是localhost,所以这里需要更改 axios设置的默认请求设置

在 main.js 文件里,设置

axios.defaults.baseURL = '/api'

配置跨域

vue.config.js文件夹要和src在同级别下

proxy代理不生效、vue config.js不生效解决方法

module.exports = {
    configureWebpack: {
        devtool: 'source-map'
    },

    productionSourceMap: false, // 生产环境是否要生成 sourceMap
    publicPath: './', //  部署应用包时的基本 URL
    outputDir: 'dist', //   打包时输出的文件目录
    assetsDir: 'assets', //   放置静态文件夹目录
    devServer: {
        host: 'localhost',
        port: 8081, //开发环境运行时的端口
        https: false, //是否启用HTTPS协议
        open: true, //项目运行成功后是否直接打开浏览器
        hot: true, //是否开启热加载
        allowedHosts: 'all',
        proxy: { //服务器代理
            '/api': {
                target: "http://localhost:8080/", // 实际跨域请求的API地址
                secure: false, // https请求则使用true
                ws: true,
                changeOrigin: true, // 跨域
                // 请求地址重写  http://front-end/api/login ⇒ http://api-url/login
                pathRewrite: {
                    '^/api': '/',
                }
            },
        }, // dev环境下,webpack-dev-server 相关配置
    }
}

在这里面 /api 就相当于’http://localhost:8080/’

所以接下来接口需要添加的的url参数不需要再写接口的域名

proxy代理不生效、vue config.js不生效解决方法

如果是封装的请求这个地址也不要写

proxy代理不生效、vue config.js不生效解决方法

要是在不行就把请求头加上

proxy代理不生效、vue config.js不生效解决方法

    headers: {
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "application/json;charset=utf-8"
    }

如果还没有办法就让后端解决

springboot解决方法

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOrigins("*")
                //是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                //跨域允许时间
                .maxAge(3600);
    }

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/41869b5351.html