can't receive monzo access token using axios

丶灬走出姿态 提交于 2019-12-13 03:58:45

问题


I've been trying for the whole day to perform a post request using axios in react (I'm trying to get an access_token for a Monzo app). I've followed the instructions here and they work perfectly when trying them out with the httpie command line tool as illustrated on said instructions. However, when I try to use it from within my react app, things go awry. The post request in question using httpie is as follows:

http --form POST "https://api.monzo.com/oauth2/token" \
"grant_type=authorization_code" \
"client_id=my_client_id" \
"client_secret=my_client_secret" \
"redirect_uri=my_redirect_uri" \
"code=my_authorization_code"

and this works as expected and returns a JSON object containing my access_token.

The (problematic) axios command I've been using in my react app is:

axios.post(
  "https://api.monzo.com/oauth2/token", {
    grant_type: "authorization_code",
    client_id: my_client_id,
    client_secret: my_client_secret,
    redirect_uri: my_redirect_uri,
    code: my_authorization_code
  })

The error message I'm getting is Failed to load resource: the server responded with a status of 400 ().

I found this very related question, which suggests I add a header specifying Content-Type: application/json so I changed my axios commands to:

axios({
  method: "POST",
  url: "https://api.monzo.com/oauth2/token",
  data: JSON.stringify({
    grant_type: "authorization_code",
    client_id: my_client_id,
    client_secret: my_client_secret,
    redirect_uri: my_redirect_uri,
    code: my_authorization_code
  }),
  headers: {
    'Content-Type': 'application/json'
  }
})

which, unfortunately, gives the exact same error.

Can anybody give me a few pointers on this? I'm very new to networking...thanks!


回答1:


And as it usually happens with these things, I found the answer shortly after posting the question. Apparently, the 'Content-Type' needs to be sent as 'application/xxx-form-urlencoded' and the data to be transformed accordingly like so:

const queryString = require('query-string')

axios({
  method: "POST",
  url: "https://api.monzo.com/oauth2/token",
  data: queryString.stringify({grant_type: ...}),
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})


来源:https://stackoverflow.com/questions/57548019/cant-receive-monzo-access-token-using-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!