gpt4 book ai didi

json - NodeJs、Express、BodyParse 和 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:34 25 4
gpt4 key购买 nike

我正在尝试使用 Express 4.0 实现一个简单的服务器并使用 BodyParser 解析消息。为了测试我的服务器,我使用 Postman。

使用 x-www-form-urlencoded 作为消息模式,它可以正常工作,但使用 JSON 更改消息我无法使用 BodyParse< 分割数据.

这是我的代码:

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
extended: true
}));

var router = express.Router()

router.get('/', function (req, res){

res.json({message: "nd..."})
})

var sendRoute = router.route('/msg')
sendRoute.post(function(req, res){

// HERE IS THE PROBLEM******************************
// It works with urlencoded request but not with JSON
var dataparam1 = req.body.param1
var dataparam2 = req.body.param2
****************************************************
.
.
.
})

假设这是我从请求中获取的 JSON 数据:

[{"param1":"This is the param1", 
"param2":"This is the param2"
}]

我的代码有什么问题吗?如何获取以 JSON 格式发送的参数?

最佳答案

如果您的请求正文作为 JSON 字符串发送,则您必须通过内容类型 header 告诉您的应用。

  1. 在 Postman 中,点击下拉菜单旁边的 Headers 按钮以选择方法和 URL params 按钮。 (右上)
  2. 表格将展开,在左侧字段中填写 Content-Type ,在右侧字段中填写 application/json
  3. 提交请求。

bodyParser 可以处理多种类型的数据,但它必须知道您提交的格式。它不会尝试猜测数据类型。

下拉菜单(根据您的评论,目前设置为“JSON”)位于您填写请求正文的文本区域上方,仅切换语法突出显示,它不会设置 Content-Type header 你。

关于json - NodeJs、Express、BodyParse 和 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26278812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com