【问题标题】:Nodejs Express req.body turns up undefinedNodejs Express req.body 出现未定义
【发布时间】:2021-01-07 03:59:01
【问题描述】:

我尝试过使用 body-parser 中间件,无论是真是假,我的 req.body 都是未定义的。尝试使用 GET 而不是 POST,仍然没有。表单具有其属性名称。我已经为此感到尴尬了一段时间,但我拒绝不解决这个问题。提前谢谢:)

当我使用 Get me 时

Webserver.js

var express = require('express');
const bp = require('body-parser');
var app = express();
var fs = require('fs');

app.use(bp.json());
app.use(bp.urlencoded({extended: true}))
app.use(express.static('pages'));


app.get('/', function(req,res)
{
    res.sendFile("pages/index.html");
    res.end();
});



app.get("/process_get", function(res,req)
{
    
    response = {
        first_name:req.body.fname
    };
    console.log(response);
    res.end(JSON.stringify(response));
});

app.post("/post_test", function(req,res)
{
    console.log("Got bodyy:", req.query.url + " " + req.body.url);
    res.sendStatus(200);
});


app.get('*',function(req,res)
{
    res.sendFile('/404.html', {root: 'pages'});
});


var server = app.listen(5000, function ()
{
    var host = server.address().address;
    var port = server.address().port;

    console.log("Listing on http://" + host + ":" + port);
})

我的html表单

<form id="survey" action = "post_test" method = "POST">
                <label for="fname">First name:</label><br>
                <input type="text" id="fname" name="fname"><br>
                <li class="button">
                    <input type = "submit" value = "Submit">
                </li>
            </form>

【问题讨论】:

    标签: node.js express request body-parser


    【解决方案1】:

    您的表单没有任何 url 字段。 试试 req.body.fname,这是表单正文中唯一的字段。

    【讨论】:

    • 谢谢,在你发帖之前我从别人那里想出来的,我放弃了发帖路线,做了一个get方法。我得到的问题是响应和请求不正常(process_get)。还了解到 body-parser 现在已弃用,并且 express 与 .json 和 .urlencoded 捆绑在一起。
    猜你喜欢
    • 2017-11-16
    • 1970-01-01
    • 2015-02-13
    • 2018-11-07
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多