允许在Android React Native上使用CORS

问题描述 投票:0回答:1

我正在使用superagent从我的React Native应用程序上传文件。它在iOS上运行正常,但在Android上却出现跨域错误。

我在https://snack.expo.io/@twohill/upload-example处创建了一个最小的示例,并复制了下面的代码以防小吃消失:

import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
import * as DocumentPicker from 'expo-document-picker';
import superagent from 'superagent';

import AssetExample from './components/AssetExample';
import { Card } from 'react-native-paper';

const upload = (file, setMessage) => {
  const { name } = file;

  superagent.post('https://example.org/uploads') // <-- change this URL to your server that accepts uploads and is CORS enabled
    .set('Authorization', 'BEARER xxxyyy') // <-- JWT token here
    .attach('uri', file, name)
    .then(
      result => setMessage(JSON.stringify({result})),
      error => setMessage(JSON.stringify({error}))
      );
};

const pickDocuments = async (setMessage) => {
  const file = await DocumentPicker.getDocumentAsync({ copyToCacheDirectory: true });
  if (file.type === "success") {
    upload(file, setMessage);
  }
}

export default class App extends Component {
  state = {
    message: null,
  }
  render() {
    const { message } = this.state;
    return (

      <View style={styles.container}>
       <TouchableOpacity onPress={() => pickDocuments(message => this.setState({message}))}>
        <Text style={styles.paragraph}>
          Tap to upload a file
        </Text>
        <Card>
          <AssetExample />
        </Card>
        <Card><Text>{message}</Text></Card>
         </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

给出错误crossDomain: true

据我所知,在Android上,该应用从未尝试上传。我的服务器运行express,并启用了cors中间件,并且具有默认配置

{
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false,
  "optionsSuccessStatus": 204
}

任何想法在这里做什么?我感觉到Android正在“ *”起源,但不知道要为移动应用程序放置什么。

或者我是完全把错误的树吠叫吗?

javascript react-native cors react-native-android superagent
1个回答
0
投票

react-native中的HTTP客户端基本上是带有JS桥的本机HTTP客户端,它没有像Web那样的CORS限制,因此您无需在快速服务器中允许CORS。

superagent而言,您似乎需要进行一些调整才能在react-native,checkout this issue中使用它>

© www.soinside.com 2019 - 2024. All rights reserved.