2016-11-26 126 views
1

無法將響應數據發送回客戶端。它拋出錯誤說response.write()不是一個函數:向nodejs中的客戶端發送響應

var express = require('express'); 
var app = express(); 
var request = require('request'); 

var port = process.env.PORT || 5000; 
app.set('port', (port)); 

app.use(express.static(__dirname + '/')); 
app.get('/', function(request, response) { 
    response.render('/'); 
}); 

app.listen(app.get('port'), function() { 
    console.log('Node app is running on port', app.get('port')); 
}); 

app.post('/login', verifyLogin); 

function verifyLogin(req, res, next) { 
    var loginParams = { 
     'username': req.body.username, 
     'password': req.body.password 
    }; 

    request({ 
     url: 'http://localhost:8084/xxx/auth', //URL to hit 
     qs: {username: req.body.username, password: req.body.password}, 
     method: 'POST', 
     json: { 
      "username": req.body.username, "password": req.body.password 
     } 
     }, function(error, response, body){ 
     if(error) { 
      console.log(error); 
     } else { 
     response.write(body); // ERROR here response.write is not a function 
     return response; 
    } 
}); 

我得到的命令提示符控制檯響應數據,但我怎麼響應數據發送回客戶端?

+0

使用response.send()或res.send()函數來代替 –

回答

2

我覺得你很困惑你的response.writeres.write

您使用的是responserequest回調,而不是resapp.post回調

4

res.send()用於發送響應到客戶端。

function verifyLogin(req, res, next) { 
    var loginParams = { 
     'username': req.body.username, 
     'password': req.body.password 
    }; 

    request({ 
     url: 'http://localhost:8084/xxx/auth', //URL to hit 
     qs: {username: req.body.username, password: req.body.password}, 
     method: 'POST', 
     json: { 
      "username": req.body.username, "password": req.body.password 
     } 
     }, function(error, response, body){ 
     if(error) { 
      console.log(error); 
     } else { 
     //response.write(body); // ERROR here response.write is not a function 

      res.send(body);// AND IT SHOULD BE USUALLY TRUE OR WITH THE OBJECT 
//SO IT CAN ALSO BE 
      res.send(true); 
//   return response; 
     } 
    }); 

例如,它被寫成

var express = require('express'); 
var app = express(); 

app.get('/', function(req, res){ 
    res.send('hello world'); 
}); 

app.listen(3000); 

這裏是參考http://expressjs.com/en/api.html

相關問題