自学内容网 自学内容网

vue项目配置配置代理解决请求接口跨域问题

使用vite搭建的vue项目配置方法。

    export default defineConfig({
        server: {
            proxy: {
                //将所有匹配 /api 的请求代理到 http://localhost:3000
                "/api": {
                    //请求的后端的服务地址
                    target: "http://localhost:3000",
                    changeOrigin: true,
                    //在进行发送请求时,会把api置空
                    //比如前端的路径为 http://localhost:3000/api/list
                    //实际发送给后端的路径为: http://localhost:3000/list
                    rewrite: (path) => path.replace(/^\/api/, ""),
                },
            },
        },
    });

使用webpace构建的vue项目

    //vue.config.js配置方法
    export default defineConfig({
        devServer: {
            proxy: {
                '/api': {
                    target: proxyDomain,
                    changeOrigin: true,
                    pathRewrite: function (path) {
                        return path.replace('/api', '');
                    }
                }
            }
        }
    })

以上的配置生效都是为了本地开发连接测试的接口,生产环境不存在这种问题。服务器可以直接转发配置即可完成跨域的问题。


原文地址:https://blog.csdn.net/m54584mnkj/article/details/143021030

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!