[英]How do i make a POST request to an api in React Native?
I am trying to make a Post request to an api but for some reason i am getting a 400 feedback in the process.我正在尝试向 api 发出 Post 请求,但由于某种原因,我在此过程中收到了 400 条反馈。 Being that i am a beginner at this, i can't really figure out where i am getting it wrong.
由于我是这方面的初学者,我真的不知道我在哪里弄错了。 I understand 400 error has to do with incorrect syntax but i am not sure that is the case here.
我知道 400 错误与不正确的语法有关,但我不确定这里的情况。 I also checked out the other related posts but none helped address my problem.
我还查看了其他相关帖子,但没有一个有助于解决我的问题。 I have also read through the documentation over and over again but still can't see where i am making a mistake.
我也一遍又一遍地阅读了文档,但仍然看不到我在哪里犯了错误。 I will appreciate if you helped me point out the problem.
如果您帮助我指出问题,我将不胜感激。
myPostRequest(){
var mybody = {
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN","partyId": "0977948551"}
}
mybody = JSON.stringify(mybody);
var token = "mytoken";
//POST request
fetch('https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay', {
method: "POST",
headers: {
'Authorization': 'Bearer '+token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
},
body: mybody,
})
.then((responseJson) => {
alert(JSON.stringify(responseJson));
console.log(responseJson);
})
.catch((error) => {
alert(JSON.stringify(error));
console.error(error);
});
}
Use axios/apisauce
instead of fetch
使用
axios/apisauce
代替fetch
apisauce
example: apisauce
示例:
import { create } from 'apisauce';
const api = create({
baseURL: `http://example.com`,
});
const response = await api.post('/path/to/', body, { headers });
In your case:在你的情况下:
import { create } from 'apisauce';
const api = create({
baseURL: `https://sandbox.momodeveloper.mtn.com`,
});
const response = await api.post(
'/collection/v1_0/requesttopay',
{
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN", "partyId": "0977948551" }
},
{
headers: {
'Authorization': 'Bearer ' + token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
}
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.