繁体   English   中英

node.js & express: req.body 未定义

[英]node.js & express: req.body undefined

我目前正在使用 express 设计一个简单的浏览器应用程序。 我正在尝试提取用户在下拉菜单中选择的值。 我也给每个选项一个单独的值,并将表单的方法声明为 /post。 但是当我通过进入req.body尝试他们选择的值时,该值未定义。

我认识到问题可能在于身体解析器浏览类似问题( ExampleExample1 ),但这些问题的解决方案并不能阻止req.body未定义。

这是我的应用程序构建代码

const app = express()
app.use(express.static(__dirname, ''));
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/public/views');
app.use(express.urlencoded());
app.set('view engine', 'html');
const server = http.createServer(app);

这是后处理的代码

app.get('/detailed', function(req,res){
    res.send(displayDetailed(results, req));
});
app.post('/detailed', function(req,res){
    res.send('Hello world');
    console.log(req.body);

});

当我在 localhost:8080/detailed 中发布内容时,hello world 返回得很好,但 req.body 为空(返回为 {})。 displayDetailed 函数是一个自定义函数,它返回一个 html 字符串,其中包含从 google 表格 API 的 get 请求中提取的值。 由于我没有使用已保存的 html 文档,这会影响流程吗?

大多数时候 req.body 由于缺少 JSON 解析器而未定义

const express = require('express');
app.use(express.json());

身体解析器可能会丢失

const bodyParser  = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

有时由于 cro 来源而未定义,因此添加它们

const cors = require('cors');
app.use(cors())

您是否设置了正文解析器以供 express 使用? 你可以 npm install body-parser 然后把它们放到你的代码中。

const bodyParser = require('body-parser')
app.use(bodyParser.json())

希望这可以帮助!

在 async 函数之外调用req.body时(调用构造 html 的函数的地方), req.body返回完美无缺。 我将修改我的项目来解决这个问题。 我应该把它放在最初的问题中,但在我写这个问题时它似乎并不相关。 感谢大家的回应

这将解决您的问题:

App.use(bodyParser.urlencoded({extended: true}));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM