Node.js 和 Express:req.body 未定义

2023-12-30

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

我认识到问题可能在于主体解析器浏览类似的问题(Example https://stackoverflow.com/questions/27320191/express4-10-bodyparser-req-body-undefined, Example1 https://stackoverflow.com/questions/27237744/node-js-express-html-form-req-body-is-undefined)但是这些问题的解决方案并没有保留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 Sheets 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}));

有时由于交叉起源而未定义,因此添加它们

const cors = require('cors');
app.use(cors())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Node.js 和 Express:req.body 未定义 的相关文章

随机推荐