在nodejs中向客户端发送响应

时间:2016-11-26 05:07:05

标签: javascript node.js

无法将响应数据发送回客户端。它的抛出错误response.write()不是函数:

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;
    }
});

我在命令提示符控制台中获取响应数据,但如何将响应数据发送回客户端?

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:4)

我认为您将response.writeres.write混为一谈?

您正在使用response回调中的request,而不是来自res回调的app.post