2017-12-04 1 views
3

사용자 이름/암호 콤보를 사용하여 서버에서 토큰을 가져와야합니다. 그런 다음 토큰을받은 후 토큰을 사용하여 두 번째 요청을 보내야합니다. 헤더. 나는이 있고, (첫 번째 요청에 호출) validLogin()에서 다음두 개의 nodejs HTTP 요청을 보내고, 두 번째는 첫 번째에 의존합니다.

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() 

과 :

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

첫 번째 요청 작품을 예상대로 응답하지만, 지금까지 내가 무엇을 가지고 두 번째 요청은 이제까지 가지 않습니다. 나는 콘솔에 인쇄하기 때문에 함수가 호출되고 있지만 요청은 아무 것도 출력하지 않는다는 것을 안다.

답변

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..."); 
    }); 
+0

(코드는 테스트하지,하지만 일반적으로 요점은 정확), 그것이 첫 번째 하나를 전송 처음 인 요청 나던 문제. 이것이 왜 그런지 알 수 있습니까? –

관련 문제