gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:21 31 4
gpt4 key购买 nike

这里是新的网络开发人员,来自 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com