使用post方法将对象发送到nodejs

时间:2017-11-02 22:35:08

标签: jquery node.js

我遇到了使用jQuery向Nodejs发送数据的麻烦。我用Postman进行了测试,但它确实有效,所以我知道我的服务器端工作正常。但是,当我尝试从我的HTML文件发送数据时,我不断收到错误:

在浏览器上:

POST http://localhost:3000/api/data 500 (Internal Server Error)

在终端上:

TypeError: Cannot read property '0' of undefined

HTML(使用Bootstrap 4):

<form>
    <input type="text" class="form-control" id="name" placeholder="Enter your name here" required>

    <select class="form-control" id="quest1" name="quest1">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>

    <select class="form-control" id="quest2" name="quest2">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>

    <button type="submit" class="btn btn-lg btn-primary submit">Submit</button>
</form>

<script>
    $('.submit').on('click', (event) => {
        event.preventDefault();

        var newData = {
        name: $("#name").val().trim(),
        scores:
            [
                parseInt($('#quest1').find(":selected").text()),
                parseInt($('#quest2').find(":selected").text())
            ]
        };

        $.post('/api/page', newData, (data) => {
        console.log(data);
        });
    });
</script>

的NodeJS:

var express = require('express');
var body = require('body-parser');
var data = require('../data/data');

var app = express();
var PORT = process.env.PORT || 3000;

app.use(body.urlencoded({extended: false}));
app.use(body.json());

app.post('/api/data', (req, res) => {
    console.log(req.body); // log result: { name: 'somebody', 'scores[]': [ '1', '2'] } 
// why is it scores[], where do the square brackets come from? and why my numbers look like strings?

    var newData = req.body.scores;
    console.log(newData); // log result: undefined obviously because the scores now have the []

//... using newData[i] in a loop hence the error above

    data.push(req.body);
    res.json(true);
});

app.listen(PORT, () => {
    console.log('Listening on PORT: ' + PORT);
});

我花了几个小时寻找解决方案。我遇到了JSON.stringify()JSON.parse()和其他建议的解决方案,但似乎没有解决方案。

  

修改

正如我上面提到的,我尝试过JSON.stringify(newData),类似于这个问题here,但它在我的情况下不起作用。日志结果显示我作为字符串中的键发送的整个数据,在对象中具有空值。

{ '{"name":"somebody","scores":[1,2]}': '' }

0 个答案:

没有答案