我目前正在使用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 /详细信息中发布内容时,hello world返回正常,但req.body为空(返回为{})。 displayDetailed函数是一个自定义函数,它返回一个html字符串,其中包含从google sheet API的get请求中提取的值。由于我没有使用已保存的html文档,这是否会影响该过程?
答案 0 :(得分:5)
大部分时间req.body由于缺少JSON解析器而未定义
const express = require('express');
app.use(express.json());
可能缺少人体分析器
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
有时由于cros来源而不确定,因此添加它们
const cors = require('cors');
app.use(cors())
答案 1 :(得分:2)
您是否设置了快速使用的正文解析器?你可以只需要安装body-parser,然后将它们放入你的代码中。
const bodyParser = require('body-parser')
app.use(bodyParser.json())
希望这有帮助!
答案 2 :(得分:0)
在异步函数(调用构造html的函数)之外调用req.body
时,req.body
返回完全正常。我将修改我的项目以解决这个问题。我应该把它放在最初的问题中,但在我写这个问题时似乎并不重要。感谢所有回复的人
答案 3 :(得分:0)
这将解决您的问题:
App.use(bodyParser.urlencoded({extended: true}));