node.js - Node.js 和 Express.js 的 POST 请求失败

标签 node.js post express

这里是新的网络开发人员,来自 C 语言的土地,一切都有点新:)

我正在进行一些 Express 学习,并且一直致力于让 POST 请求正常工作。我在 Chrome 上使用 Advanced Rest Client 发送 POST 请求,但收到错误,没有错误号,只是简单的“计算机说不”。

我的app.js:

var express = require('express')
    , http = require('http');

var app = express();

app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    app.use(express.urlencoded());
    app.use(express.json());
});

app.get("/", function(req, res) {
    res.send("Hello, Express!");
});

app.get("/hi", function(req, res) {
    var message = "Hello :-)";
    res.send(message);
});

app.get("/users/:userId", function(req, res) {
    res.send("<h1>Hello user #" + req.params.userId);
});

app.post("/users", function(req, res) {
    res.send("Creating a new user with name " + req.body.username);
});

http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
});

所有其他路由都有效,只是 POST 失败。

编辑:另外,我在发布时使用 text/html 作为内容类型。

我已重新启动服务器,确保保存文件,重新启动系统等。我猜测问题是正文解析失败。任何帮助都会很棒,干杯。

最佳答案

express.json() 不会解析 text/html,因此您的路由处理程序中没有 req.body,并且req.body.username 行将引发错误。

I've restarted the server, ensured the file is saved, rebooted the system etc. I'm guessing the issue is the parsing of the body is failing.

别猜。调试和读取日志 (app.use(express.logger('dev')));

关于node.js - Node.js 和 Express.js 的 POST 请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22268641/

相关文章:

node.js - 具有单个数据库的多个 Node 实例

javascript - PHP 和 javascript 组合变量问题

python - Python 中的 HTTP POST

javascript - 使用 EJS 的 ExpressJS 在 AWS Amplify 上部署时无法加载静态 Assets

javascript - 为什么当我使用 koajs 时触发控制台两次

node.js - 无法加载资源: the server responded with a status of 426 (Upgrade Required)

php - 如何在网页之间传递 '&amp;'数据

node.js - Nodejs 应用程序中未定义请求

node.js - 如何使用 forEach() 发送 res.send() 数组

node.js - 使用 Express 将文件上传保存到 Mongo DB