Home > Blockchain >  send post request from react native
send post request from react native

Time:12-26

fetch('ADDRESS', {
  method: 'POST',
  headers: {
    'STW-Authorization': 'Basic YmFybmk6YmFybmkxNTY=',
  },
  body: `<?xml version='1.0' encoding='Windows-1250'?>
  <dat:dataPack>
  ...
  </dat:dataPack>`,
})
.then(response => response.text())
.then(data => {
  //var xml = new XMLParser().parseFromString(data);    // Assume xmlText contains the example XML
  console.log(data);
})
.catch(err => console.error(err));


`

how can i send body with post method. because this what i writed code it is not working. and when i get the response how can i parse in react native

CodePudding user response:

To send a POST request with a body in React Native, you can use the fetch() function with the following parameters:

  • The url of the server you want to make the request to. An options
  • object with the following properties:
    • method: set to 'POST' to send a POST request.
    • headers: an object containing any headers you want to include in the request.
    • body: the data you want to send in the body of the request. In this case, it looks like you want to send an XML string. Here's an example of how you might send the request with the fetch() function:

fetch('ADDRESS', {
  method: 'POST',
  headers: {
    'STW-Authorization': 'Basic YmFybmk6YmFybmkxNTY=',
    'Content-Type': 'text/xml' // set the content type to XML
  },
  body: `<?xml version='1.0' encoding='Windows-1250'?>`
})
  .then(response => response.text())
  .then(data => {
    console.log(data)
    // parse the XML here, using a library like xml2js or xmldom
  })
  .catch(err => console.error(err))

To parse the XML response, you can use a library like xml2js or xmldom. Here's an example of how you might use xml2js to parse the response:

import xml2js from 'react-native-xml2js';

fetch('ADDRESS', {
  method: 'POST',
  headers: {
    'STW-Authorization': 'Basic YmFybmk6YmFybmkxNTY=',
    'Content-Type': 'text/xml',
  },
  body: `<?xml version='1.0' encoding='Windows-1250'?>
  <dat:dataPack>
  ...
  </dat:dataPack>`,
})
.then(response => response.text())
.then(data => {
  xml2js.parseString(data, (err, result) => {
    if (err) {
      console.error(err);
    } else {
      console.log(result);
      // do something with the parsed XML
    }
  });
})
.catch(err => console.error(err));
  • Related