1. 问题描述 先说下问题,项目后端是微型Python框架flask,前端是vue-element, 本地开发我配置的是proxy代理,代码如下:
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
before: require('./mock/mock-server.js'),
proxy: {
'/dev-api/api/': {
target: `http://192.168.1.171:5100`,
changeOrigin: true,
pathRewrite: {
'/dev-api/api/': '/api/'
}
}
}
},
下面post请求接口: 用Postman直接请求是没问题的,如下图: 控制台打印的日志: 但是不知道为啥页面上请求超时,报错400:
后台无法接收到json格式参数,如下图:
报错信息:
Proxy error: Could not proxy request /api// from localhost:9525 to http://... (ECONNRESET)
2. 解决办法:
修改vue.config.js文件,改动代码如下:
devServer: {
host: 'localhost',
port: port,
overlay: {
warnings: false,
errors: true
},
before: require('./mock/mock-server.js'),
proxy: {
'/dev-api/api': {
target: `http://192.168.1.171:5100`,
changeOrigin: true,
onProxyReq:function (proxyReq, req, res, options) {
if (req.body) {
let bodyData = JSON.stringify(req.body);
proxyReq.setHeader('Content-Type','application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
},
pathRewrite: {
'^/dev-api/api': '/api'
}
}
}
},
再次请求,成功~~
参考博客:nodejs中http-proxy使用小结
|