【问题标题】:How do i get json data from HTML to Nodejs server如何从 HTML 获取 json 数据到 Nodejs 服务器
【发布时间】:2019-12-13 17:13:27
【问题描述】:

我创建了一个 UI 来使用 HTML 读取、写入和更新配置文件,但我无法将新的 JSON 对象保存到我现有的配置文件中。

所以我需要将 JSON 对象从 HTML 文件发布到 nodejs 服务器

JAVASCRIPT

 var testJson = { name: "mufashid" }
        $.ajax({
            url: 'http://localhost:3000/test/config',
            type: 'POST',
            dataType: 'json',
            data: { o: JSON.stringify(testJson ) }, // bags collection value what your goging to send to server 
            // crossDomain: true,
            success: function (data) {
                alert('Success!')
            },
            error: function (jqXHR, textStatus, err) {
                //show error message
                alert('text status ' + textStatus + ', err ' + err)
            }
        });

nodejs


app.post('/test/config', function (req, res) {
    // console.log(res);
    console.log(req)

})

按下保存按钮时需要使用新值更新配置文件。

【问题讨论】:

  • 你试过req.data吗?你可以尝试使用console.log来调试
  • @Shinjo 是的,我试过 req.data 它显示未定义。
  • console.log(req) 返回什么?
  • 你添加app.use(require('express').json())了吗?
  • 你的 (res) 呢?可以帮忙:stackoverflow.com/questions/45105992/…stackoverflow.com/questions/13478464/…。一旦您能够从 ajax 请求访问您的 json,您就可以轻松地操作数据。

标签: jquery html node.js


【解决方案1】:

您在 JavaScript 代码中遗漏了contentType: "application/json"

var testJson = { name: "mufashid" }
        $.ajax({
            url: 'http://localhost:3000/test/config',
            type: 'POST',
            contentType: "application/json",// you missed this line.
            dataType: 'json',
            data: JSON.stringify({ o: testJson }), // IMportant!!!!!!
            // crossDomain: true,
            success: function (data) {
                alert('Success!')
            },
            error: function (jqXHR, textStatus, err) {
                //show error message
                alert('text status ' + textStatus + ', err ' + err)
            }
        });

【讨论】:

    【解决方案2】:

    请找到以下代码。缺少内容类型

    $.ajax({
        url: 'http://localhost:3000/test/config',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify({
          o: testJson
        }),
        // crossDomain: true,
        success: function (data) {
          alert('Success!')
        },
        error: function (jqXHR, textStatus, err) {
          //show error message
          alert('text status ' + textStatus + ', err ' + err)
        }
      });
    

    路线

    app.post('/test/config', function (req, res) {
      console.log(req.body.o);
    })
    

    【讨论】:

      猜你喜欢
      • 2015-04-25
      • 2012-07-19
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 2020-12-11
      • 2016-08-03
      • 1970-01-01
      相关资源
      最近更新 更多