gpt4 book ai didi

Trouble getting past CORS error in Django(在Django很难通过CORS错误)

转载 作者:bug小助手 更新时间:2023-10-25 22:05:07 26 4
gpt4 key购买 nike



I'm getting a CORS error whilst trying to use React with Django and postgresql. I have tried many ways to configure the CORS settings in Django however nothing seems to work. When I made a simple route that passes "Hi" it works. So I am not sure if there is an error with my view or something is wrong with the front end at React. I have also ensured that the VITE_SERVER is correct by console logging it and that my endpoints used are accurate.

在尝试将Reaction与Django和PostgreSQL一起使用时,我收到了CORS错误。我尝试了很多方法来配置Django中的CORS设置,但似乎都不起作用。当我做了一条简单的路线经过“Hi”时,它起作用了。所以我不确定是我的观点有误,还是Reaction的前端有问题。我还通过控制台记录来确保vite_server是正确的,并且我使用的端点是准确的。


This are my Django settings:

以下是我的Django设置:


    ALLOWED_HOSTS = []

CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = [
'content-type',
'authorization',
]
CORS_ALLOWED_ALL_ORIGINS = True
ALLOWED_HOSTS = [
"127.0.0.1",
]

CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:8000/"]


AUTH_USER_MODEL = 'customers.CustomerAccount'


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'customers',
'dealer',
'restful_apis',
]


REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}


MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

This is my fetch hook that I used:

这是我使用的FETCH钩子:


import React from "react";

const useFetch = () => {
const fetchData = async (endpoint, method, body, token) => {
const res = await fetch(import.meta.env.VITE_SERVER + endpoint, {
// mode: "no-cors",
method,
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
body: JSON.stringify(body),
});
const data = await res.json();

let returnValue = {};
if (res.ok) {
if (data.status === "error") {
returnValue = { ok: false, data: data.msg };
} else {
returnValue = { ok: true, data };
}
} else {
if (data?.errors && Array.isArray(data.errors)) {
const messages = data.errors.map((item) => item.msg);
returnValue = { ok: false, data: messages };
} else if (data?.status === "error") {
returnValue = { ok: false, data: data.message || data.msg };
} else {
console.log(data);
returnValue = { ok: false, data: "An error has occurred" };
}
}

return returnValue;
};

return fetchData;
};

export default useFetch;

Here is my view that does not work:

以下是我的观点,但并不奏效:


 class CarRentalListView(views.APIView):
authentication_classes = []
permission_classes = [AllowAny]
def get(self, request):
rentals = RentalListing.objects.all()
serialized_data = []

for rental in rentals:
rental_data = RentalListingSerializer(rental).data
car_data = CarSerializer(rental.car_id).data

combined_data = {
"rentallisting_id": rental_data.get("id"),
"rental_rate": rental_data.get("rental_rate"),
"drive_to_malaysia": rental_data.get("drive_to_malaysia"),
"listing_date": rental_data.get("listing_date"),
"vehicle_id": car_data.get("car_id"),
"brand": car_data.get("brand"),
"model": car_data.get("model"),
"colour": car_data.get("colour"),
"vehicle_type": car_data.get("vehicle_type"),
"vehicle_image": car_data.get("vehicle_image"),
"seat_capacity": car_data.get("seat_capacity"),
}

serialized_data.append(combined_data)

return (Response(serialized_data, status=status.HTTP_200_OK))

Here is the view that works. I am able to receive the data in my browser console:

以下是可行的观点。我可以在我的浏览器控制台中接收数据:


class TestRoute(views.APIView):
authentication_classes = []
permission_classes = [AllowAny]

def get(self, request):
return Response("Hi")

Finally on React this is how I am calling the endpoint.(I have checked to see if the endpoints work in Postman and also double checked the enpoints in React):

最后,在Reaction上,这是我调用终结点的方式。(我已经检查了终结点在Postman中是否正常工作,并再次检查了Reaction中的终结点):


    const Home = () => {
const fetchData = useFetch();
const [rentals, setRentals] = useState([]);

const getRentals = async () => {
const res = await fetchData("/dealer/cars/rentals", "GET", undefined);
if (res.ok) {
setRentals(res.data);
console.log(res.data);
} else {
alert(JSON.stringify(res.data));
console.log(res.data);
}
};

useEffect(() => {
getRentals();
console.log(import.meta.env.VITE_SERVER);
}, []);

Finally, this is the CORS error my browser throws me:

最后,这是浏览器向我抛出的CORS错误:


Access to fetch at 'http://127.0.0.1:8000/dealer/cars/rentals' from origin 'http://localhost:5173' has been blocked by CORS policy: 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.

更多回答
优秀答案推荐

I noticed that the CORS error was prevelant only when I used a particular Google account on Chrome. When I switched chrome accounts the data was able to go through to the front end and logged on my chrome developer console. As such upon more digging I found that the solution was to enable ALLOW CORS:Access Control extension in my google chrome browser with the main account I was using.

我注意到,只有当我在Chrome上使用特定的谷歌账户时,CORS错误才会流行。当我切换Chrome账号时,数据可以通过前端并登录到我的Chrome开发人员控制台。因此,在进一步挖掘后,我发现解决方案是使用我使用的主帐户在我的Google Chrome浏览器中启用允许CORS:访问控制扩展。


https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

Https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf


更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com