用fetch()响应本地API请求以获取API在poster中响应良好,但在应用程序中不起作用,并得到400个错误



我正在尝试将KYC流的mati-api集成到我的React原生应用程序中。为了获得auth令牌,我参考了下面的文档。https://docs.getmati.com/reference/authenticationposter中的测试运行良好,并得到auth_token的响应。然而,在React本机代码中,它得到了400个错误。请帮我弄清楚。代码片段:

const myoptions = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA',
},
body: new URLSearchParams({grant_type: 'client_credentials'}),
};
fetch('https://api.getmati.com/oauth', myoptions)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));

错误为:

LOG  {"code": 400, "message": "Missing parameter: `grant_type`", "name": "invalid_request", "status": 400, "statusCode": 400}

从您提到的文档来看,它似乎正在接受表单数据,并且您正在发送搜索参数。试试这个

const formData = new FormData();
formData.append("grant_type","client_credentials");
const myoptions = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA',
},
body: formData,
};
fetch('https://api.getmati.com/oauth', myoptions)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));

我发现了错误,并计算如下。

const body = new URLSearchParams({grant_type: 'client_credentials'});
const myoptions = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA',
},
body: body.toString(),
};
fetch('https://api.getmati.com/oauth', myoptions)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));

在react native中,我们必须将主体作为字符串发送,它运行良好并得到正确的响应。非常感谢。