本文介绍了使用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未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 09:53