gpt4 book ai didi

node.js - 请求正文在 Node Express 中未定义

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

在 Node Express 中,当我尝试从表单访问发布值时,它显示请求正文未定义错误。这是我的代码,

http.createServer(function(req, res) {
var hostname = req.headers.host.split(":")[0];
var pathname = url.parse(req.url).pathname;

if (pathname==="/login" && req.method ==="POST") {
console.log("request Header==>" + req.body.username );

}).listen(9000, function() {
console.log('http://localhost:9000');
});

请任何人帮我找出为什么请求正文显示未定义。

最佳答案

启用body-parser首先是中间件

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})

关于node.js - 请求正文在 Node Express 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37044556/

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