React native get API端点总是400而没有body

时间:2017-03-30 11:40:25

标签: javascript react-native fetch axios

我有一个正常工作的CURL请求:

curl -v -X POST https://auth.domain.com/v1/oauth/tokens -u test:test -d "grant_type=authorization_code" -d "code=d9a473a4-e417-4dd7-9151-83e9c1cb9ca6" -d "redirect_uri=app://authorize"

我尝试在我的React Native应用程序中实现它,但我总是得到400错误。首先我使用了axios:

var url = `https://auth.domain.com/v1/oauth/tokens`
axios.post(url, {
  "grant_type": 'authorization_code',
  "code": code,
  "redirect_uri": 'app://authorize',
},{
  auth: {
    username: 'test',
    password: 'test'
  }
}).then(response => {
  console.log(response);
}).catch(function(error) {
  console.log('There has been a problem with your fetch operation: ' + error.message);
  throw error
});

但我得到400错误:

Possible Unhandled Promise Rejection (id: 0):
Request failed with status code 400
Error: Request failed with status code 400

我尝试使用fetch:

fetch(url, {
  method: 'post',
  headers: {
    'Authorization': 'Basic '+btoa('test:test'), 
  },
    body: JSON.stringify({
      "grant_type": 'authorization_code',
      "code": code,
      "redirect_uri": 'app://authorize',
    })
  }).then(response => {
    console.log('Request core...');
    console.log(response);
  })

我用相同的空身体得到400错误。对于CURL请求,我得到200 OK以及来自服务器的响应。我在JS方面做错了什么?

2 个答案:

答案 0 :(得分:1)

此代码对我有用。

.catch((error) => console.log( error.response.request._response ) );

答案 1 :(得分:0)

正如Yury Tarabanko所指出的那样,问题是"您正在使用curl发送urlencoded数据。其他例子发送json。 "

解决方案:

var url = `https://auth.domain.com/v1/oauth/tokens`
axios.post(url, 
  querystring.stringify({
    "grant_type": 'authorization_code',
    "code": code,
    "redirect_uri": 'app://authorize',
  }),{
    auth: {
      username: 'test',
      password: 'test'
    },
    headers: {
      'Content-type': 'application/x-www-form-urlencoded'
    }
  }).then(response => {
    console.log('Request core...');
    console.log(response);
  }).catch(function(error) {
    console.log('There has been a problem with your fetch operation: ' + error.message);
    console.log(error);
    throw error;
});