【问题标题】:Source.headers is not supported when using POST使用 POST 时不支持 Source.headers
【发布时间】:2019-03-06 12:32:55
【问题描述】:

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

来自文档:

" headers (object) - 与请求一起发送的附加 HTTP 标头。在 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
    }}
  />
);

【问题讨论】:

  • 您是否通过邮递员或其他 REST 客户端获得了结果?
  • 是的,它适用于邮递员。

标签: react-native webview react-native-android


【解决方案1】:

您可以使用 WebView 的自定义扩展,如 Send Post request along with HttpHeaders on Android 中所述(请参阅重复的问题以获取其他答案)。

【讨论】:

    【解决方案2】:

    解决此限制的一种方法是在 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;
    );
    

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

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

    【讨论】:

    • 谢谢。我不知道 response.text() 是一个承诺。
    • 虽然使用WebView 不是一种优雅的方式,但我无法让它以另一种方式工作。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多