我目前正在使用express 设计一个简单的浏览器应用程序。我正在尝试提取用户在下拉菜单中选择的值。我也给每个选项一个单独的值,并将表单的方法声明为/post。但是当我尝试进入 req.body
来选择他们选择的值时,该值是未定义的。
我认识到问题可能在于主体解析器浏览类似问题( Example 、 Example1 ),但这些问题的解决方案并不能阻止 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 文档,这会影响该过程吗?
最佳答案
大多数情况下,由于缺少 JSON 解析器,req.body 未定义
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())
关于javascript - node.js & Express : req. 主体未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50569718/