Unexpected token N in JSON at position 0

1

Guys I have an error that in my NodeJS rest API, and can not resolve this. My idea is to do a github login, this application works like this:

  • Redirection to github by returning a temporary code in callback.

  • Send this temporary code to my REST API and make a search request to another endpoint of the GitHub API. This request must return access_token = 12345 (this access token is an example), to send this token to the frontend, convert it to a JWT token and then store it in a localStorage to use it.

My code in NodeJS

router.post("/users/github/:code",function(req,res){
    fetch('https://github.com/login/oauth/access_token/', {
        method: 'GET',
        client_id: 'xxxx',
        client_secret: 'xxxx',
        code: req.params.code,
        accept: 'json',
    })
   .then(function(res) {
        return res.json();
    }).then(function(json) {
        console.log(json);
    });
 
});

PS: I use% co_of% module for this. link

    
asked by Santiago D'Antuoni 27.01.2017 в 18:37
source

1 answer

1

Your request is wrong, the right thing is like this:

fetch('https://github.com/login/oauth/access_token/', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      client_id: 'xxxx',
      client_secret: 'xxxx',
      code: req.params.code
    })
})
  .then(function(res) {
      return res.json();
  }).then(function(json) {
      console.log(json);
  });
});

Look at the headers and body section. In a POST request, you must send the data in the body ( body ) of the request. In case you send a JSON, you must parse it to string (by means of JSON.stringify ) and, in addition, you must specify the Content-Type of the information you are sending, in your case application/json .

  

By default the GitHub API returns plain text in response , but you can specify what type of data you want to receive by means of the header Accept :

headers: {
  Accept: 'application/json',
  'Content-Type': 'application/json'
}
    
answered by 27.01.2017 / 18:44
source