使用express bodyParser后,request.body未定义

编程入门 行业动态 更新时间:2024-10-28 21:31:19
本文介绍了使用express bodyParser后,request.body未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我通过使用以下方式修复了该问题:

i fixed it by using:

app.configure(function(){ app.use(express.bodyParser()); });

原始帖子:

我试图弄清楚如何使用node和express处理帖子,而我完全陷入困境.

I'm trying to figure out how to handle a post with node and express and i'm completely stuck.

经过一番阅读后,我注意到人们说我应该使用中间件",并创建一行 app.use(express.bodyParser()); .我假设添加后,我的post方法中将有一个 req.body 可用.但是事实并非如此.将console.log放入 undefined .

After some reading i noticed people saying i should use 'middleware' whatever that means and create a line app.use(express.bodyParser());. I assumed that after adding that i would have a req.body available in my post method. This isn't the case however. It console.log's into a undefined.

我想我不知道如何正确设置它,所以这里什么也没做:

I think I don't know how to properly set this up, so here goes nothing:

var express = require('express') , routes = require('./routes') , user = require('./routes/user') , http = require('http') , path = require('path') , UserProvider = require('./userprovider').UserProvider, qs = require('querystring'); var userProvider = new UserProvider('localhost', 27017); var app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server); server.listen(8080); app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); app.get('/new_game', function (req, res) { res.sendfile(__dirname + '/new_game.html'); }); app.post('/new_game', function(req, res) { var codeToUse = Math.random()*10000; codeToUse = Math.round(codeToUse); console.log(req.body); }); app.use(express.bodyParser()); app.listen(3000);

推荐答案

尽管您已经说过您的代码可以使用,但是我不建议您在选项中使用bodyParser.

Though you've said now your code works, but i won't suggest you to use bodyParser in the options of

app.configure()

它的作用是,如果您按已使用的方式使用它,则任何文件都可以发送到您的系统中以用于所有发帖请求.最好使用

What it does is that, if you use it as you have done, any file can be send into your system for all post requests. It's better if you use

express.json()

express.urlencoded()

在以下选项中 app.configure(),并且当您期望文件在这样的各个发布路径中使用bodyParser

in the options of app.configure(), and when you expect a file use bodyParser in the respective post route like this

app.post('/upload', express.bodyParser(), function(req, res){//do something with req.files})

更多推荐

使用express bodyParser后,request.body未定义

本文发布于:2023-10-11 22:10:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1482981.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未定义   bodyParser   express   body   request

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!