【问题标题】:How to receive (and decode) JSON from post data in Node.Js Express?如何从 Node.Js Express 中的 post 数据接收(和解码)JSON?
【发布时间】:2017-11-19 05:12:39
【问题描述】:

假设我使用以下代码发送了数据:

        $.ajax({
            type: "POST",
            url: "/save/" + #{key},
            data: transitions2,
            success: function (data) {

            },
            dataType: "json"
        });

transitions2 是分层 JS 对象。

现在我怎样才能在服务器端完整接收它

router.post('/save/:key', function(req, res) {
    // where is my data here?    
});

更新

我找到了有关正文解析器的信息,并发现我的网站模板已经包含它们。特别是,app.js 包含:

...
var bodyParser = require('body-parser');
...
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/data', express.static(path.join(__dirname, '../data')));

app.use('/', index);
...

所以我写在我的index.js:

...
router.post('/save/:key', function(req, res) {
    var transitions = req.body;
    image_data.save_transitions(req.params.key, req.query.postfix, transitions);
});
...

很遗憾,transitions 包含

在客户端它包含

即充满了数据。

可能是什么问题?

更新 2

我试过了

        $.ajax({
            type: "POST",
            url: "/save/" + #{key},
            data: JSON.stringify(transitions2),
            success: function (data) {

            }
        });

我现在在Fiddler2 中看到,完整的 Json 已通过。

[{"start_image":"20170402_1_NATURAL_COL0R","end_image":"20170409_1_NATURAL_COL0R","transition_classes":["no_transition","some_activity"]},...

不幸的是,在服务器端,我观察到字符串被截断和损坏

(等号不应在 JSON 中)。

JSON.parse 失败。

【问题讨论】:

  • @dan 不能与正文解析器一起使用
  • 您是否尝试过在发送 JSON 之前对其进行字符串化?即用data: JSON.stringify(transitions2)替换data: transitions2
  • @dan yes 刚刚尝试失败
  • @dan 请看我的更新

标签: json node.js express post


【解决方案1】:

使用 body-parser 中间件检索数据。

npm install body-parser

在 express 应用中进行配置。

在下面找到示例代码

var bodyParser = require('body-parser');
app.use(bodyParser.json());

然后在您的路由器中使用以下内容:

 router.post('/save/:key', function(req, res) {
        var data = req.body // here is your data   
    });

【讨论】:

  • 是的,我找到了这个,但没有帮助。
【解决方案2】:

问题仅出在客户端。使用 json 发布复杂对象的正确方法是:

        $.ajax({
            type: "POST",
            url: "/save/" + #{key},
            data: JSON.stringify(transitions2),
            contentType: "application/json; charset=utf-8",
            success: function (data) {

            }
        });

stringifycontentType 是必填项。

【讨论】:

    【解决方案3】:

    正面:

    axios.post('/attack', {
            number:number,
            count:count
            }, 
            {
                headers:{contentType: "application/json; charset=utf-8"}
            })
            .then((response) => {
                console.log(response);
            })
            .catch((error) => {
                console.log(error);
            });
    }
    

    返回:

    const express = require('express')
    const bodyParser = require('body-parser')
    const app = express()
    
    app.use(bodyParser.json())
    
    app.post('/attack', (req, res) => {
        let data = req.body
        console.log(data)
        res.send('200')
    })
    

    控制台日志:{ number: '(number)', count: '(count)' }

    【讨论】:

      猜你喜欢
      • 2012-02-03
      • 2017-02-19
      • 1970-01-01
      • 2017-02-21
      • 2019-04-22
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      相关资源
      最近更新 更多