Javascript React native get API端点始终为400,无正文
我有一个正常工作的卷曲请求:Javascript React native get API端点始终为400,无正文,javascript,react-native,fetch,axios,Javascript,React Native,Fetch,Axios,我有一个正常工作的卷曲请求: 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原生应用程序中实现它,但我总是收到400个错误。首先,我使用了axios:
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原生应用程序中实现它,但我总是收到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端做错了什么?正如前面提到的,问题是“您正在使用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;
});
此代码适用于我。
.catch((error) => console.log( error.response.request._response ) );
您正在使用curl发送URL编码的数据。其他示例发送json。谢谢,这就是问题所在。