我遇到一个问题,即无论我使用何种正文解析器设置,提交表单的发帖请求都会生成一个空正文。我的 package.json 依赖项都是最新的,我以前制作的一个应用程序(使用已弃用的 app.use(bodyParser);)可以毫无问题地执行此操作。我一直在研究 SO 和各种网站并尝试每一种破解方法,但似乎没有任何效果。
这是我的 app.js 的相关部分:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var routes = require('./routes/routes.js');
app.post('/checklogin',routes.post_checklogin);
这是在发布请求时调用的路由函数:
var checkLogin = function(req,res) {
console.log(req.body)
}
这是我试图从中获取我的表单的表单,在哈巴狗中模板化:
form(action="/checklogin" method="post" enctype="application/x-www-form-urlencoded")
input(id="login-email" class="form-control" type="text" placeholder="email")
input(id="login-password" class="form-control" type="text" placeholder="password")
button(id="login-submit" class='btn btn-primary') Login
无论 enctype 或 body 解析器设置的什么组合都允许我将“{}”以外的任何内容作为 req.body。如果有人能指出我想象中的一个非常愚蠢的错误,我将永远感激不已。
此外,我意识到这可能不是处理登录的最佳方式,但这只是为了让 POST 请求在整个应用程序中正常工作。
最佳答案
这不是 body-parser
问题,您在 input
元素上缺少 name
属性。
A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.
input(id="login-email" name="email" class="form-control" type="text" placeholder="email")
input(id="login-password" name="password" class="form-control" type="text" placeholder="password")
关于javascript - Node.js express路由POST请求空体,使用body-parser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50205275/