Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

node.js - Nodejs Express req.body turns up undefined

I have tried playing around with the body-parser middleware, no matter what is true or false I get my req.body as undefined. Tries going working with GET instead of POST, still nothing. The form has its name for the attribute. I have been at this for an embarrassing amount of time but I refuse to not fix this. Thx in advance :)

When I worked with the 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);
})

My html form

<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>
question from:https://stackoverflow.com/questions/65602434/nodejs-express-req-body-turns-up-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your form does not have any url field. Try req.body.fname which is the only field you've got in the form body.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...