json - webpack-dev-server (devServer) 没有收到来自 axios 的 json 数据 (payload) | req.query & req.params 为空
问题描述
我有一个 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));
});
}
}
}
等效的 axios 调用就像
axios.post('/my/route', {bar1: 'x', bar2: 'y'}).then(...) => {...})
我能够到达路线,因为我得到了console.log(CircularJSON.stringify(req))
输出,但是req.query
&req.params
是空的。我怀疑这是因为我正在发送 JSON 数据,但即使有额外的 axios 配置{headers: { 'Content-Type': 'application/json' }}
,我也无法获得我想要发送的数据。
任何想法 ?
解决方案
解决方案是使用“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));
});
}
}
}
推荐阅读
- java - JPA WrongArgumentException:SQL 字符串不能为 NULL:尽管 CrudRepository 保存函数接收填充的实体
- r - 绘制 geom_line() + geom_point() R
- javascript - 为什么在我的 jQuery 循环中返回不起作用?
- amazon-web-services - 使用 AWS Java SDK 获取 DynamoDB 中的列值计数
- knockout.js - Uncaught (in promise) ReferenceError: ValidationBase is not defined
- android - 运行 Ionic cordova 时出现无限循环 run android --livereload
- node.js - express 接收 favicon.ico 作为默认路由的参数
- sql - 有没有一种方法可以按 id 升序保存我的表格
- r - 使用列内的固定效果信息重塑 R 中的数据
- google-apps-script - 在 Chrome 扩展程序中使用 Google Apps 脚本