likes
comments
collection
share

vue.config.js proxy里的pathRewrite

作者站长头像
站长
· 阅读数 89

不论是vue.config.js还是vite.config.js中都有前端跨域的配置。 vue.config.js中有

proxy: {
    '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        ws: true,
        pathRewrite: {
            '^/api': ''  
        }
    }
}
        

问:pathRewrite 里面的 '^/api' 是什么意思 答:用代理首先你得有一个标识,表明你的这个连接要使用代理,不然的话 html css js 这些静态资源都跑去代理。 /api 就是告诉 node ,我接口用 /api 开头的才使用代理,所以接口都写成 /api/xx/xx ,最后代理的路径就是 http://localhost:3000/api/xx/xx

可是不对呀,我正确的接口路径里面是没有 /api 的,所以就需要 pathRewrite , 用 ^/api: ''/api 去掉,这样既能有正确的标识,又能在请求接口的时候去掉 /api

注:在浏览器的DevTools中查看接口,并不能显示出来真实的代理路径。

vue.config.js proxy里的pathRewrite

拆解一下DevTools中Request URL, http://localhost:1840 ,这是发起请求的服务地址 /api/user/login ,这是请求的路径地址, 而真实的请求地址实际为: http://localhost:3000/user/login

以上,有参考至:https://www.cnblogs.com/hanguidong/p/9460495.html