发送两个Node.js的HTTP请求,第二个请求依赖于第一个请求

3
我需要使用用户名/密码组合从服务器获取令牌,然后在收到令牌后,我需要发送第二个请求,使用令牌作为头部内容。目前为止,这是我所拥有的:
var requestData = {
    'username': 'myUser',
    'password': 'myPassword1234'
}

var options = {
    hostname: 'localhost',
    port: 8080,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    }
}

var req = http.request(options, function(res) {
    console.log("Status: " + res.statusCode)
    res.setEncoding('utf8');
    let body = ""
    res.on('data', function (data) {
        if (res.statusCode == 200) {
            console.log("Success")
            body += data
        } else {
            invalidLogin()
        }
    })
    res.on('end', function () {
        body = JSON.parse(body)
        console.log("DONE")
        console.log(body)
        validLogin(body["token"])
    })
})
req.on('error', function(e) {
    console.log('error: ' + e.message)
})
req.write(JSON.stringify(requestData))
req.end()

然后在validLogin()函数中(此函数在第一个请求中被调用),我有以下代码:

function validLogin(token) {
console.log(token)

var options = {
    hostname: 'localhost',
    port: 8080,
    path: '/dashboard',
    method: 'GET',
    headers: {
        'Authorization': token,
    }
}

var req = http.request(options, function(res) {
    console.log("Status: " + res.statusCode)
    res.setEncoding('utf8');
    let body = ""
    res.on('data', function (data) {
        if (res.statusCode == 200) {
            body += data
        } else {
            console.log(body)
        }
    })
    res.on('end', function() {
        console.log(body)
    })
})
req.on('error', function(e) {
    console.log('error: ' + e.message)
})
req.end()
}

第一个请求按预期工作并响应,但第二个请求永远不会执行。我知道该函数被调用了,因为它会在控制台打印,但请求没有输出任何内容。

1个回答

0

我会使用request-promise,它可以很方便地将请求链接在一起。(代码未经测试,但大致准确)

var rp = require('request-promise');

var options_login = {
  hostname: 'localhost',
  port: 8080,
  path: '/login',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  payload: JSON.stringify(requestData),
  json: true
};

var options_request = {
    hostname: 'localhost',
    port: 8080,
    path: '/dashboard',
    method: 'GET',
    json: true
};

rp(options)
  .catch(function(parsedBody){
     console.log("Error logging in.");
  })
  .then(function(parsedBody) {
     options_request.headers = {
       'Authorization': parsedBody.token,
     };

     return rp(options_request);
  })
  .catch(function(err) {
      console.log("Loading the dashboard failed...");
  });

我尝试查看了您的示例和其他一些示例,但它只发送第一个请求,无论哪个请求先到都只发送第一个请求。您知道这可能是什么原因吗? - Mike Smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接