javascript - Node.js express路由POST请求空体,使用body-parser

标签 javascript node.js rest express post

我遇到一个问题,即无论我使用何种正文解析器设置,提交表单的发帖请求都会生成一个空正文。我的 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 属性。

取自W3C specification :

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/

相关文章:

node.js - 如何使用 adonis 更改列类型而不丢失迁移中的数据库数据?

api - Paypal - 使用 REST API 从沙盒切换到真实账户

android - 使用 Node.JS 服务器验证 Android 应用程序检索到的 Google 访问 token

java - 在现有 PHP 服务器上构建 REST Java API

python - py2neo - neo4j.GraphDatabaseService(db_string) 使 python 崩溃;没有错误日志

javascript - [Custom Directive]将 scope.$watch on link 与 scope.$watch on controller 的区别

javascript - 将 Float32Array 转换为缓冲区

javascript同步执行

javascript - 如何更改为空格

node.js - Angular 2 指令作为 npm 包