【问题标题】:How to send JSON to NodeJS Express Server through Postman?如何通过 Postman 将 JSON 发送到 NodeJS Express 服务器?
【发布时间】:2016-02-26 12:49:42
【问题描述】:

我正在尝试从 Chrome 应用程序“邮递员”通过 POST 发送 JSON 对象。

如果我将header设置为'Content-Type: text/plain',那么另一边的输出就是一个空对象:

{}

如果我将标头设置为Content-Type: application/json,我会收到以下响应...

'错误:无效的 json'。

key设置为ingredients,value设置为:

{ ["name" : "num1", "quantity" : "5"], ["name" : "num2", "quantity" : "2"], [ "name" : "num3", "quantity" : "8"]}

我在这里抓住了它:

router.post('/add', jsonParser, function( req, res ) {

     if (!req.body) return res.sendStatus(400);    
     console.log( req.body );
});

【问题讨论】:

  • 你能详细说明什么是jsonParser吗?像var jsonParser = bodyParser.json() 吗?

标签: javascript json node.js express body-parser


【解决方案1】:

您的 JSON 无效。重组为既能正确解析又能继续工作的东西。下面的示例应该可以正常工作,您的对象数组存储在ingredients...

{
    "ingredients": [{
        "name": "num1",
        "quantity": "5"
    }, {
        "name": "num2",
        "quantity": "2"
    }, {
        "name": "num3",
        "quantity": "8"
    }]
}

您可以随意切换它,只要确保它解析即可。 JSONLint 将成为您的朋友。即使是没有命名标识符的普通数组也可以工作,而且我越看它,就好像你只是把你的 {} 和 [] 语法倒退了......

[{"name": "num1", "quantity": "5"}, {"name": "num2","quantity": "2"}, {"name": "num3","quantity": "8"}]

【讨论】:

  • 这也不起作用 { "ingredients": [{"name" : "num1", "quantity" : "5"}, {"name" : "num2", "quantity" : “2”},{“名称”:“num3”,“数量”:“8”}]}
  • 我给了你原始的 json 对象。这是根本问题,而不是如何与邮递员即插即用。不管怎样,我看到你想通了
【解决方案2】:

首先,您需要根据您的模型设计数据。 使用http://jsoneditoronline.org/ 格式化Json,不会出现语法错误

第 1 步:- 设置 Url 参数(如果有)

第 2 步:- 设置标准 Http 标头

示例:- 1)。内容类型:应用程序/json 2)。接受:应用程序/json

然后根据您的要求使用 http CRUD 操作

您需要将数据发送到 POST 和 PUT 操作 Get - 可以获取 json 来自 api

Post Ex:- 选择 Post with API 你会看到 3 个选项 form-data x-www-form-urlencoded raw 选择选项“raw”并粘贴您的 Json 内容

祝你好运!!

【讨论】:

  • 多做一些研究,让您了解好友快乐学习!!
猜你喜欢
  • 2016-01-30
  • 2013-12-27
  • 2021-06-18
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多