5

enter image description here

I wanted to send a POST request to my backend with webview. How do i get but i got the above error.

From the docs:

" headers (object) - Additional HTTP headers to send with the request. On Android, this can only be used with GET requests."

How do i get a work-around for this ?

this is my code

const data = JSON.stringify({
  type: 'car',
  plate_number: 'c123'
});

return (
  <WebView
    source={{
      uri:'https://api-stg.caspian.id/user/vehicles/add',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: '54dc3c3c*******'
      },
      body: data
    }}
  />
);
william anputra
  • 159
  • 1
  • 4
  • 12

2 Answers2

4

One way to get around this limitation is by performing this POST request in the React Native side of things, waiting for this response to arrive, and then feed the response HTML into the WebView directly:

// Here using the fetch API as base, but you can use any
// library you want that is able to perform HTTP requests
constructor(props, ctx) {
  super(props, ctx);
  this.state = { html: null };
}

componentDidMount() {
  const data = JSON.stringify({
    type: 'car',
    plate_number: 'c123'
  });
  fetch('https://api-stg.caspian.id/user/vehicles/add', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: '54dc3c3c*******'
    },
    body: data,
  }).then(response => response.text()).then(text => {
    this.setState({ html: text });
  });
}

render() {
  return this.state.html ? (
    <WebView
      source={{
        html: this.state.html,
        baseUrl: 'https://api-stg.caspian.id/user/vehicles/add',
      }}
      originWhitelist={['*']}
    />
   ) : /* loading UI */ null;
);

Here are the WebView's docs regarding the source property and how to put a static HTML in there:

https://facebook.github.io/react-native/docs/webview#source

rsalmeidafl
  • 411
  • 2
  • 4
0

You can use a custom extension of WebView, as described in Send Post request along with HttpHeaders on Android (see the duplicate questions for other answers).

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307