【问题标题】:empty json when using body-parser bodyParser.json()使用 body-parser bodyParser.json() 时为空 json
【发布时间】:2021-01-11 12:54:51
【问题描述】:

我正在尝试通过 HTML 页面中的脚本将长 json 作为发布请求发送:(数据来自文本框,它是正确的 json 数组)

<script>
        /* UPDATE ORGANIZATION LIST*/
        function updateOrgs () {
            var data = $('#showOrgs').val();

            $.ajax({
                url : "http://localhost:8000/api/updateOrgs",
                type: "POST", // data type (can be get, post, put, delete)
                data : {json:JSON.parse(data)}, // data in json format
                async : false, // enable or disable async (optional, but suggested as false if you need to populate data afterwards)
                success: function(response, textStatus, jqXHR) {
                    alert(response);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown)
                }
            });
        }        
</script>

我已将我的快递设置为:

const express = require('express');
var bodyParser = require('body-parser')
// initialize express
const app = express();

// body-parser
// create application/json parser
var jsonParser = bodyParser.json()
 
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({extended: false})

我在我的 node express 应用程序中使用 body-parser 来读取正文中的 json,例如:

app.post('/api/updateOrgs', jsonParser, (req, res)=> {
    try {
        console.log(req.body);
        // send response
        res.send('Successfully updated');
    } catch (e) {
        res.send(e);
    }
});

问题是我的快递应用打印了一个空对象{}。那么是因为我发布的json文件很大吗?它在一个数组中有 64 个对象。

或者问题来自使用使用body-parser模块作为app.post('/api/updateOrgs', jsonParser, (req, res)=&gt; {的express应用程序?

【问题讨论】:

  • 您可能缺少 Content-Type: application/json 标头
  • 对小json有用吗?

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


【解决方案1】:

试试看:

dataType: 'json',
contentType: 'application/json',
data : JSON.stringify({json:JSON.parse(data)}),

所有代码:

<script>
        /* UPDATE ORGANIZATION LIST*/
        function updateOrgs () {
            var data = $('#showOrgs').val();

            $.ajax({
                url : "http://localhost:8000/api/updateOrgs",
                type: "POST", // data type (can be get, post, put, delete)
                dataType: 'json',
                contentType: 'application/json',
                data : JSON.stringify({json:JSON.parse(data)}), // data in json format
                async : false, // enable or disable async (optional, but suggested as false if you need to populate data afterwards)
                success: function(response, textStatus, jqXHR) {
                    alert(response);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown)
                }
            });
        }        
</script>

【讨论】:

    【解决方案2】:

    bodyParser 对象公开了各种工厂来创建中间件。当 Content-Type 请求标头与 type 选项匹配时,所有中间件都将使用解析后的 body 填充 req.body 属性,如果没有要解析的正文,则 Content-Type 不匹配,或者是一个空对象 ({})发生错误。

    bodyParser.json([options])

    返回仅解析 json 并且仅查看 Content-Type 标头与 type 选项匹配的请求的中间件。此解析器接受正文的任何​​ Unicode 编码,并支持 gzip 和 deflate 编码的自动膨胀。

    在中间件之后的请求对象上填充一个包含解析数据的新主体对象(即 req.body)。

    var express = require('express')
    var bodyParser = require('body-parser')
    
    var app = express()
    
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }))
    
    // parse application/json
    app.use(bodyParser.json())
    // POST /login gets urlencoded bodies
    app.post('/login', urlencodedParser, function (req, res) {
      res.send('welcome, ' + req.body.username)
    })
    
    // POST /api/users gets JSON bodies
    app.post('/api/users', jsonParser, function (req, res) {
      // create user in req.body
    })
    

    更改解析器接受的类型

    var express = require('express')
    var bodyParser = require('body-parser')
    
    var app = express()
    
    // parse various different custom JSON types as JSON
    app.use(bodyParser.json({ type: 'application/*+json' }))
    
    // parse some custom thing into a Buffer
    app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
    
    // parse an HTML body into a string
    app.use(bodyParser.text({ type: 'text/html' }))
    

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 2020-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多