Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source.headers is not supported when using POST

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
    }}
  />
);
like image 538
william anputra Avatar asked Oct 01 '18 11:10

william anputra


1 Answers

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

like image 178
rsalmeidafl Avatar answered Nov 03 '22 20:11

rsalmeidafl