我正在写一个相对较新的应用程序,并想知道我应该使用哪个:
express.json()
要么
bodyParser.json()
我可以假设他们做同样的事情.
我想使用express.json()已经内置的内容.
我正在使用中间件body-parser对表单值进行编码以获取req.body对象.但是当我调试我的代码时,发现req.body是未定义的.这是我的代码
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
Run Code Online (Sandbox Code Playgroud)
收听发帖请求
app.post('/newCategory', function (req,res) {
//express attached the form encoded values into body
var categoryName = req.body.categoryName;
});
Run Code Online (Sandbox Code Playgroud)
Html表格
<form action="/newCategory" role="form" method="post" class="form-inline">
<input type="text" name="categoryName" placeholder="Category name" class="form-control" />
<input type="submit" value="New Category" class="btn btn-primary" />
</form>
Run Code Online (Sandbox Code Playgroud) 我使用的是 Express 4.13.3,并且req.body在 GET 请求中 my 始终为空。它填充了 POST 请求的正确数据。为什么是这样?我在 Express 文档中找不到任何关于此差异的参考。
我的 Express 配置:
function onError(err, req, res, next) { // eslint-disable-line no-unused-vars
// The error id is attached to `res.sentry` to be returned
// and optionally displayed to the user for support.
res.statusCode = 500; // eslint-disable-line no-param-reassign
res.end(`${res.sentry}\n`);
}
const render = require('../public/assets/SSR');
const app = express();
// sentry.io
app.use(raven.middleware.express.requestHandler(process.env.SENTRY_DSN));
const db = connectDb();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(cookieParser());
if (process.env.NODE_ENV …Run Code Online (Sandbox Code Playgroud) 我目前正在使用 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);
Run Code Online (Sandbox Code Playgroud)
这是后处理的代码
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);
});
Run Code Online (Sandbox Code Playgroud)
当我在 localhost:8080/detailed 中发布内容时,hello world 返回得很好,但 req.body 为空(返回为 {})。displayDetailed 函数是一个自定义函数,它返回一个 html 字符串,其中包含从来自 google sheet API 的 get 请求中提取的值。由于我没有使用保存的 html 文档,这会影响流程吗?