【发布时间】:2023-01-03 04:14:25
【问题描述】:
我有一个 Django 应用程序和一个 React 本机应用程序。我正在从 android studio 运行 android 模拟器。
现在我尝试将后端与前端连接起来。我研究了这个例子: https://reactnative.dev/docs/network
示例网址:https://reactnative.dev/movies.json' 有效。
我在端口上运行 native-react 应用程序:http://192.168.1.69:19000/ 我在端口上运行后端:http://127.0.0.1:8000/api/movies/
但现在我尝试连接我自己的本地主机数据。所以这是我的组件:
import { ActivityIndicator, FlatList, Text, View } from "react-native";
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: true,
};
}
async getMovies() {
try {
const response = await fetch("http://127.0.0.1:8000/api/movies/", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
const json = await response.json();
this.setState({ data: json.movies });
} catch (error) {
console.log(error);
} finally {
this.setState({ isLoading: false });
}
}
componentDidMount() {
this.getMovies();
}
render() {
const { data, isLoading } = this.state;
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => <Text>{item.title}</Text>}
/>
)}
</View>
);
}
}
这是邮递员的数据:
[
{
"id": 1,
"title": "Husband",
"description": "Very nice wife cocks the man",
"no_of_ratings": 1,
"avg_rating": 5.0
},
{
"id": 2,
"title": "Nice movie",
"description": "Description ah, niceNICE",
"no_of_ratings": 0,
"avg_rating": 0
}
]
但是如果我尝试运行这个例子。我收到此错误:
Access to fetch at 'http://127.0.0.1:8000/api/movies/' from origin 'http://localhost:19006' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
问题:如何使本地连接与后端反应?
【问题讨论】:
-
我试过:10.0.2.2:3000/api/movies 和 10.0.2.2:8080/api/movies。但是还是报错cannot fetch data
-
使用您系统的 IP 地址作为基本 url
-
@拉格纳。你到底什么意思? react-native 使用的是:Metro waiting on exp://192.168.1.69:19000 在我使用的浏览器中:localhost:19006
标签: python django react-native android-studio