req.body.name未定义

编程入门 行业动态 更新时间:2024-10-28 17:22:35
本文介绍了req.body.name未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

你好,我有一个要发送到服务器的表格,但是当它到达处理程序时.我尝试打印出内容,但正文未定义.请有人可以我做错了.

Hello i have a form that i am sending to the server but when it reaches the handler. I try to print out the contents but the body is undefined. Please could someone what i did wrong.

<form action="/myactive" method="POST"> <input type="radio" name="gender" value="Male"> Male<br> <input type="radio" name="gender" value="Female"> Female <button type="submit" class="btn btn-primary btn-md">Medium</button> </form>

在我的服务器端下方是:

and below my server side is:

var express = require('express'); var app = express(); var bodyparser = require('body-parser'); app.set('port', process.env.PORT || 3030); app.use(bodyparser.urlencoded({ extended: false })); app.use(express.static(__dirname + '/public')); app.get('/', function(req, res) { console.log('Index page'); }); app.post('/myaction', function(req, res){ console.log('Name: '+req.body.name); //returns undefined res.end("Welcome"); }); app.listen(app.get('port'), function(){ console.log('Listening on port '+app.get('port')); });

但是在控制台上它会打印

But on the console it prints

Name is undefined.

推荐答案

您需要在表单中指定与服务器中的发布路线相同的action.所以/myactive -> /myaction.此外,在req.body对象中没有name属性.当您在表单中指定name="gender"时,这意味着gender属性将附加到req.body对象

You need to specify the same action in your form with the post route that you have in the server. So /myactive -> /myaction. Moreover there is no name property in the req.body object. When you specify name="gender" in your form it means that the gender property will be attached to the req.body object

<form action="/myaction" method="POST"> <input type="radio" name="gender" value="Male"> Male<br> <input type="radio" name="gender" value="Female"> Female <button type="submit" class="btn btn-primary btn-md">Medium</button> </form>

您可以使用以下代码从路线中检索所选性别

And you can retrieve the selected gender from your route using below code

app.post("/myaction", function(request, response) { console.log("Gender is:", request.body.gender); response.sendStatus(200) });

更多推荐

req.body.name未定义

本文发布于:2023-10-11 22:10:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1482983.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未定义   req   body

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!