如何在React Native中向api发出POST请求?

时间:2020-06-27 22:13:36

标签: json react-native rest fetch-api

我正在尝试向api发送Post请求,但是由于某种原因,我在此过程中收到400条反馈。由于我是这个方面的初学者,因此我无法弄清楚我在哪里弄错了。我了解400错误与语法错误有关,但我不确定情况是否如此。我还查看了其他相关帖子,但没有一个帮助解决我的问题。我也一遍又一遍地阅读了文档,但仍然看不到我在哪里犯错。如果您能帮助我指出问题,我将不胜感激。

  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);
    });
  }

1 个答案:

答案 0 :(得分:0)

使用axios/apisauce代替fetch

apisauce示例:

import { create } from 'apisauce';

const api = create({
  baseURL: `http://example.com`,
});

const response = await api.post('/path/to/', body, { headers });

在您的情况下:


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',
        }
    }
);