webpack-dev-server的proxy代理404

听说webpack-dev-server可以转发线上接口,尝试了一下,为啥404?

devServer: {
    port: 7777,
    host: '127.0.0.1',
    historyApiFallback: true,
    proxy: {
        '/json': {
            target: 'http://wx.xxxx.cn/api/',
            secure: false,
            changeOrigin: true
        }
    }
}
fetch('/json/LightLuxuryIndexData?cityid=321', {
    method: 'get'
})
    .then(res => res.json())
    .then(data => {
        //do sth...
    })

clipboard.png

看了其他几个类似的问题,加上这个pathRewrite: { "^/json": "" }解决了,具体为啥还在看文档。

仔细对比了一下官方文档,问题出在这里:

官方文档:
/api ===> http://localhost:3000
/api/users ===> http://localhost:3000/api/users(注意这里是/api/users,而不是/users)

/json ===> http://wx.xxxx.cn/api/
/json/XXX ===> http://wx.xxxx.cn/api/json/XXX (所以这里实际被转发到/json/XXX,而实际接口地址是http://wx.xxxx.cn/api/XXX,所以要用pathRewrite: {"^/json" : ""}把'/json'拿掉)

阅读 8k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题