【问题标题】:accessing post data on node server?访问节点服务器上的发布数据?
【发布时间】:2017-03-05 00:18:21
【问题描述】:

我正在尝试使用 AJAX 将简单的表单数据发送到节点/快递服务器。提交时,我被带到无法发布 / 页面,虽然我能够 console.log 一个请求,但它不包含表单中的数据。我错过了什么?

表格

<form method="POST" class="form-group">
    <label for="sentenceCount">Sentences</label>
     <input type="number" placeholder="10" name="sentence count" id="sentenceCount" class="form-control parameters">
  <button type="submit" id="submit" class="btn btn-primary mt-1">Submit</button>

</form>

AJAX 请求 $('button').on('click', function(data) {

            $.ajax({
                data: data,
                url: '/data',
               type: "POST"

            })
        }

    )

服务器.js

var express = require('express');
var app = express();
app.listen(8000)

app.get('/', function (req, res) {
    res.sendFile('/Index.html', {
        root: __dirname
    })
});

app.post('/data', function (req, res) {
    console.log(req)
})

更新:

我摆弄了一下,能够访问 body 属性,但 body 是空的,无法获得我需要的输入值。

AJAX:

 $('button').on('click', function(data) {
         var formData = $('input').val();
        console.log(formData)

            $.ajax({
                data: formData,
                url: '/data',
               type: "post"

            })
        }

    )

服务器:

app.get('/', function (req, res) {
res.sendFile('/Index.html', {
    root: __dirname
})
});

    app.use(bodyParser.json())

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

【问题讨论】:

    标签: javascript ajax node.js express


    【解决方案1】:

    你忘记了正文解析器。

    1. 安装body-parsernpm i body-parser
    2. 在快速路由之前添加正文解析器 JSON 中间件。

    例子:

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

    并且表单数据应该是一个用 JSON 编码的对象:

     $('button').on('click', function(data) {
         var formData = $('input').val();
            $.ajax({
                data: {value: formData},
                url: '/data',
               type: "post"
    
            })
        }
    
    )
    

    【讨论】:

    • 谢谢。几个问题:为什么你使用 app.get() 表单是一个发布请求?当我使用 .get 时,没有记录任何内容,但使用 post 记录。然而,柱子上的尸体是空的。知道为什么数据没有通过吗?
    • 1.修复获取/发布问题。 2. 表单数据不是有效的 JSON。
    猜你喜欢
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    相关资源
    最近更新 更多