2014-10-07 90 views
0

我正在製作GCM應用程序,所以當我需要服務器來匹配公平時。節點js:HTTP POST:錯誤:發送後無法設置標題

有一個由Node js創建的代碼。

var http = require('http'); 
var express = require('express'); 
var app = express(); 
app.use(express.static('public')); 
app.use(express.bodyParser()); 
app.use(app.router); 
var gcm = require('node-gcm'); 
var message = new gcm.Message(); 
var message = new gcm.Message({ 
    collapseKey: 'demo', 
    delayWhileIdle: true, 
    timeToLive: 3, 
    data: { 
     key1: '안녕하세요.', 
     key2: 'saltfactory push demo' 
     } 
    }); 

var server_access_key = '~'; 
var sender = new gcm.Sender(server_access_key); 
var registrationIds = []; 

var registration_id = '~-~-~-~-~~~-~'; 
// At least one required 
registrationIds.push(registration_id); 

app.post('/enroll',function(request,response){ 
var my_number = Number(request.param('myphonenumber')); 
var another_number = Number(request.param('anotherphonenumber')); 

console.log(my_number); 
console.log(another_number); 

response.send(my_number); 
response.send(another_number); 
response.json({success:1}); 
response.json({success:"my_number"}); 
response.json({success:"another_number"}); 

}); 

http.createServer(app).listen(52273,function(){ 
    console.log('Server Running'); 
}); 

當我在POST-MAN執行POST,我得到什麼瀏覽器和 我的終端顯示此錯誤代碼:

NaN 
    NaN 
    Error: Can't set headers after they are sent. 
at ServerResponse.OutgoingMessage.setHeader (http.js:689:11) 
at ServerResponse.res.setHeader (/Users/~) 
at ServerResponse.res.set.res.header (/Users/~) 
at ServerResponse.res.send (/Users/~) 
at ServerResponse.res.json (/Users/~) 
at /Users/~ 
at callbacks (/Users/~) 
at param (/Users/~) 
at pass (/Users/~) 
at Router._dispatch (/Users/~) 

NaN被通過

console.log(my_number); 
console.log(another_number); 

我造成的不知道爲什麼NaN印刷。我明明Insert鍵:myphonenumber,anotherphonenumber &值:12345678,98765432.

+0

嘗試發送'response'只有一次,你可以創建一個普通的對象並存儲所有的數據。所以不要在調用中多次使用'.send'或'.json'。關於'NaN',我認爲你沒有得到響應,請嘗試'request'對象上的'console.log'。 – Ravi 2014-10-07 09:20:05

回答

1

不能使用response.json或response.send方法超過一次

app.post('/enroll/:myphonenumber/:anotherphonenumber',function(request,response){ 
    var my_number = Number(request.params.myphonenumber); 
    var another_number = Number(request.params.anotherphonenumber); 
    console.log(my_number); 
    console.log(another_number); 
    response.json({'my_number':my_number,'another_number':another_number,success:1}); 
}); 
相關問題