【问题标题】:How to communicate django api with frontend react native?如何将 django api 与前端 react native 通信?
【发布时间】: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.

问题:如何使本地连接与后端反应?

【问题讨论】:

标签: python django react-native android-studio


【解决方案1】:

按照步骤设置 CORS 并直接调用您的应用程序端点。

1.) 设置后端端点以接受和显示来自传入请求的数据。 i.) 首先做一些像这样的 pip install :pip install django-cors-headers ii.) 在您的settings.py 文件中,将以下代码添加到您的文件中

INSTALLED_APPS = [
    
             ...
    
             'corsheaders',
    
            ...
    
            ]

iii.) 将 CORS 中间件添加到 django 文件

MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  ...
  'django.middleware.clickjacking.XFrameOptionsMiddleware',
  'corsheaders.middleware.CorsMiddleware', //<== Add this
    ]

iv.) 添加CORS_ORIGIN_ALLOW_ALL = True到settings.py

v.) 现在每个应用程序都可以访问端点。

2.) 让你的 fetch 变成这样

getMovies = async () => {
    var url = 'http://127.0.0.1:8000/api/movies/';

    fetch(url, {
      method: 'GET',
      mode: 'cors',
      headers: {
        'Content-type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      },
    })
      .then(response => response.json())
      .then(responseJson => {
        setTransaction_details(responseJson);
        setLoading(false);
      });
  };

【讨论】:

    猜你喜欢
    • 2016-11-30
    • 2020-12-05
    • 2019-11-17
    • 2020-07-15
    • 1970-01-01
    • 2016-12-07
    • 2019-11-13
    • 2020-09-24
    • 1970-01-01
    相关资源
    最近更新 更多