[英]webpack-dev-server (devServer) doesn't receive json data (payload) from axios | req.query & req.params are empty
I have a webpack-dev-server config like我有一个 webpack-dev-server 配置,例如
const path = require('path')
const CircularJSON = require('circular-json') //just to allow me to log circular references
module.exports = {
...
devServer: {
before(app) {
app.all('/my/route', (req, res) => {
console.log(CircularJSON.stringify(req))//req.query & req.params are empty {}
// I wanna have access to sent payload from Axios here, eg:
const result = {
foo1: req.query.bar1,
foo2: req.query.bar2
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
});
}
}
}
The equivalent axios call is like等效的 axios 调用就像
axios.post('/my/route', {bar1: 'x', bar2: 'y'}).then(...) => {...})
I'm able to hit the route because I got the console.log(CircularJSON.stringify(req))
output, but the req.query
& req.params
are empty.我能够成功,因为我得到了
console.log(CircularJSON.stringify(req))
output,但是req.query
& req.params
是空的。 I suspect it is due to the fact that I was sending JSON data, but even with extra axios config {headers: { 'Content-Type': 'application/json' }}
I couldn't get the data I wanna send.我怀疑这是因为我发送了 JSON 数据,但即使有额外的 axios 配置
{headers: { 'Content-Type': 'application/json' }}
我无法获得我想要发送的数据。
Any idea?任何想法?
the solution was to use 'body-parser'解决方案是使用“body-parser”
const path = require('path')
const CircularJSON = require('circular-json') //just to allow me to log circular references
const bodyParser = require('body-parser')
module.exports = {
...
devServer: {
before(app) {
// use bodyParser for axios request
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.all('/my/route', (req, res) => {
console.log(CircularJSON.stringify(req))//req.query & req.params are empty {}
// access them on req.body:
const result = {
foo1: req.body.bar1,
foo2: req.body.bar2
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
});
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.