2013-07-14 35 views
0

我是新的節點js &快遞。我今天能夠獲得我的第一個Node JS表單,並且按預期工作。所以我想在Express上重新創建相同的內容,但由於某種原因,我在編程上失敗了。我能夠跟蹤標題和內容,但由於某種原因,我無法理解爲什麼Express會重寫正文的處理方式。快遞正在重寫身體上捲曲電話

我在添加我的發現。下面是代碼,這是通過快速命令行工具生成的。這是app.js文件,方法上傳正在尋找一些數據。我目前沒有處理任何文件上傳,我只是在尋找一些遇到的文字。

/** 
* Module dependencies. 
*/ 

var express = require('express') 
    , routes = require('./routes') 
    , user = require('./routes/user') 
    , http = require('http') 
    , path = require('path'); 

var app = express(); 

// all environments 
app.set('port', process.env.PORT || 3000); 
app.set('views', __dirname + '/views'); 
app.set('view engine', 'jade'); 
app.use(express.favicon()); 
app.use(express.logger('dev')); 
app.use(express.bodyParser()); 
app.use(express.methodOverride()); 
app.use(app.router); 
app.use(express.static(path.join(__dirname, 'public'))); 

// development only 
if ('development' == app.get('env')) { 
    app.use(express.errorHandler()); 
} 

app.get('/', routes.index); 
app.get('/users', user.list); 



/**custom stuff**/ 

app.post('/upload',function(req, res){ 
     console.log(req.header('Content-Type')); 
     console.log(req.header('Host')); 
     console.log(req.header('User-Agent')); 

     console.log(req.body); 
     res.send("Hello the response is "+req.body.username); 
}); 

/** end**/ 

http.createServer(app).listen(app.get('port'), function(){ 
    console.log('Express server listening on port ' + app.get('port')); 
}); 

現在我對函數進行卷曲調用。

curl -d '{"username":"myname"}' -H 'Content-Type: application/x-www-form-urlencoded' http://localhost:3000/upload 

而這些都是集流管和所述主體。(頭終止於3線,主體是在第4行)

application/x-www-form-urlencoded 
localhost:3000 
curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3 
{ '{"username":"myname"}': '' } 
POST /upload 200 7ms - 36b 

現在,我使用Advanced Rest Client App谷歌瀏覽器和下面是報頭和身體。

application/x-www-form-urlencoded 
localhost:3000 
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36 
{ username: 'myname from adv rest client app' } 
POST /upload 200 5ms - 58b 

所以,一件事是困惑我是爲什麼,而從我的請求,身體被扭曲的身體由其他客戶端應用程序的請求得到很好的形成和完整。任何人都可以幫我解決這個問題。

謝謝

+0

嘗試爲['-D「用戶名= myname'' ](http://superuser.com/a/149335)或['-H'Content-Type:application/json''](http://stackoverflow.com/a/477819),也許?否則,您使用的數據格式(JSON)和指定的格式(URL編碼)之間似乎不匹配。 –

+0

Got it!這是問題所在。你可以補充說,作爲答案,所以我可以關閉這個問題 – macha

回答

0

的問題可能是在curl命令的數據/頭組合,似乎有使用(JSON)的數據格式之間的不匹配:

-d '{"username":"myname"}' 

而指定格式(URL編碼):

-H 'Content-Type: application/x-www-form-urlencoded' 

對於URL-encoded data,嘗試:

-d 'username=myname' 

而且,因爲你有文件上傳的工作,你可能想要指定multipart/form-data或使用該設置它的-F/--form option

curl -F 'username=myname' http://localhost:3000/upload