node.js&表达:req.body未定义 [英] node.js & express: req.body undefined

查看:52
本文介绍了node.js&表达:req.body未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently designing a simple browser application utilizing express. I'm trying to extract the value a user selects in a drop down menu. I gave each option an individual value as well and have declared the method of the form as /post. but when I try which value they selected by going into the req.body, the value is undefined.

我认识到问题可能出在浏览类似问题的正文解析器中(示例 Example1 ),但这些问题的解决方案不会使 req.body 处于不确定状态.

I recognize that the problem could lie with the body parser from browsing through similar questions (Example, Example1) but the solutions from these questions don't keep req.body from being undefined.

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

Here's my code for the app construction

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中发布内容时,您好世界返回的很好,但是req.body为空(返回为{}).displayDetailed函数是一个自定义函数,它返回一个html字符串,其值是从Google Sheets API的get请求中提取的.由于我不使用保存的html文档,这会影响过程吗?

When I post something in localhost:8080/detailed, the hello world returns just fine, but req.body is an empty (returns as {}). The displayDetailed function is a custom function that returns a html string with values extracted from a get request from the google sheets API. Since I'm not working with a saved html document, could this be affecting the process?

推荐答案

由于缺少JSON解析器,大部分时间req.body都未定义

Most of the time req.body is undefined due to missing JSON parser

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

人体分析器可能缺少

could be missing for the body-parser

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

有时由于cros来源而不确定,因此添加它们

and sometimes it's undefined due to cros origin so add them

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

这篇关于node.js&表达:req.body未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆