简体   繁体   English

在nodejs中向客户端发送响应

[英]Send response to client in nodejs

Unable to send response data back to client. 无法将响应数据发送回客户端。 Its throwing error saying response.write() is not a function: 抛出错误说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;
    }
});

I am getting the response data in command prompt console but how do I send response data back to client? 我在命令提示符控制台中获取响应数据,但如何将响应数据发送回客户端?

res.send() is used to send response to the client. 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;
        }
    });

For instance, It is written as 例如,它写成

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

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

app.listen(3000);

Here is the reference http://expressjs.com/en/api.html 这是参考http://expressjs.com/en/api.html

I think you're confusing your response.write with res.write ? 我想你混淆你response.writeres.write

You're using the response from the request callback, and not the res from the app.post callback 您正在使用request回调中的response ,而不是来自app.post回调的res

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM