2012-06-04 2 views
4

Google에서 인증해야하는 노드 애플리케이션을 개발 중입니다. 나는 컬에서 같은 요청을 해봤과 같은 오류를받은oauth2 토큰 요청이 잘못되었습니다.

error: 400 
{ 
    "error" : "invalid_request" 
} 

, 그래서 나는 내 요청에 문제가 의심하지만 난 할 수 없습니다 : 나는 토큰을 요청하면 함께 https://accounts.google.com/o/oauth2/token는 응답 무엇을 알아 내라. 아래에 내 코드를 붙여 넣었습니다.

var request = require('request'); 
var token_request='code='+req['query']['code']+ 
        '&client_id={client id}'+ 
        '&client_secret={client secret}'+ 
        '&redirect_uri=http%3A%2F%2Fmassiveboom.com:3000'+ 
        '&grant_type=authorization_code'; 
request(
    { method: 'POST', 
     uri:'https://accounts.google.com/o/oauth2/token', 
     body: token_request 
    }, 
    function (error, response, body) { 
     if(response.statusCode == 201){ 
      console.log('document fetched'); 
      console.log(body); 
     } else { 
      console.log('error: '+ response.statusCode); 
      console.log(body); 
     } 
    }); 

제출 한 모든 데이터가 올바른지, 여전히 동일한 오류가 발생하는지 확인하기 위해 세 번 검사했습니다. 더 이상 디버깅하려면 어떻게해야합니까?

+0

여기에 token_request var.that에서 생성 된 최종 문자열이 잘못되었을 수 있습니다. – sudmong

답변

3

request.js (https://github.com/mikeal/request)는 헤더에 content-length를 자동으로 포함하지 않습니다. 수동으로 추가했고 첫 번째 시도에서 작동했습니다. 아래에 코드를 붙여 넣었습니다.

exports.get_token = function(req,success,fail){ 
    var token; 
    var request = require('request'); 
    var credentials = require('../config/credentials'); 
    var google_credentials=credentials.fetch('google'); 
    var token_request='code='+req['query']['code']+ 
     '&client_id='+google_credentials['client_id']+ 
     '&client_secret='+google_credentials['client_secret']+ 
     '&redirect_uri=http%3A%2F%2Fmyurl.com:3000%2Fauth'+ 
     '&grant_type=authorization_code'; 
    var request_length = token_request.length; 
    console.log("requesting: "+token_request); 
    request(
     { method: 'POST', 
      headers: {'Content-length': request_length, 'Content-type':'application/x-www-form-urlencoded'}, 
      uri:'https://accounts.google.com/o/oauth2/token', 
      body: token_request 
     }, 
     function (error, response, body) { 
      if(response.statusCode == 200){ 
       console.log('document fetched'); 
       token=body['access_token']; 
       store_token(body); 
       if(success){ 
        success(token); 
       } 
      } 
      else { 
       console.log('error: '+ response.statusCode); 
       console.log(body) 
       if(fail){ 
        fail(); 
       } 
      } 
     } 
    ); 
} 
+0

두 번째 헤더로 'node.js의 HTTP POST 요청'에있는 예 : –

+0

POST 예제가 Google에서 필요로하는 모든 헤더를 전송하지 않았기 때문에 POST 예제가 작동하지 않았습니다. – devnill

0

여기에 게시물 token_request var.that에서 생성 된 최종 문자열이 뭔가 잘못되었을 수 있습니다. 인증 코드가 만료되었거나 URL에 올바르게 추가되지 않았을 수 있습니다. 일반적으로 코드에는 이스케이프해야하는 '/'기호가 있습니다.

1

여기에서 How to make an HTTP POST request in node.js?querystring.stringify을 사용하면 요청 매개 변수의 쿼리 문자열을 이스케이프 처리 할 수 ​​있습니다. 또한 POST 요청에 'Content-Type': 'application/x-www-form-urlencoded'을 추가하는 것이 좋습니다.

+0

기본 콘텐츠 형식으로 추가하기 위해 양식으로 제출하려면 require를 사용했지만 여전히 실패했습니다. – devnill

관련 문제