使用 POST 时不支持 Source.headers

wil*_*tra 5 webview react-native react-native-android

在此处输入图片说明

我想用 webview 向我的后端发送一个 POST 请求。我怎么得到,但我得到了上述错误。

从文档:

" headers (object) - 与请求一起发送的额外 HTTP headers。在 Android 上,这只能与 GET 请求一起使用。"

我如何解决这个问题?

这是我的代码

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
    }}
  />
);
Run Code Online (Sandbox Code Playgroud)

小智 4

解决此限制的一种方法是在 React Native 端执行此 POST 请求,等待此响应到达,然后将响应 HTML 直接输入到 WebView 中:

// 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;
);
Run Code Online (Sandbox Code Playgroud)

以下是有关源属性以及如何在其中放置静态 HTML 的 WebView 文档:

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