简体   繁体   中英

localhost: 3000 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. REACT and DJANGO

I am able to get list of objects on http://127.0.0.1:8000/api/todos running on DJANGO,

I wanna product detail page with id, http://127.0.0.1:8000/api/todos/14 .

http://127.0.0.1:8000/api/todos/14 . works fine in POSTMAN, and even in chrome. but in react I get

Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/todos/14' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am using Axios.

Product.js

const [dataItems, setDataItems] = useState([]);
useEffect(() => {
axios
  .get("http://127.0.0.1:8000/api/todos/")
  .then((res) => {
    console.log(res);
    setDataItems(res.data);
  })
  .catch((err) => {
    console.log(err);
  });

}, []);

ProductDetail.js

const [detailItems, setDetailsItems] = useState([]);
useEffect(() => {
    axios.get("http://127.0.0.1:8000/api/todos/14").then((res) => {
       console.log(res);
    });
    }, []);

I have installed django-cors-headers and http://127.0.0.1:8000/api/todos this work fine. Here is my settings.xml for cors-headers.

Settings.xml

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hero.apps.HeroConfig',
'rest_framework.authtoken',
'users.apps.UsersConfig',
'rest_framework',
'corsheaders',

]

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


]

CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000'
]

ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False

urls.py

from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'todos', views.TodoView, 'todo')

urlpatterns = [

    path('api/', include(router.urls)),
    path('', views.home),
]

views.py

from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'todos', views.TodoView, 'todo')

urlpatterns = [

path('api/', include(router.urls)),
]

Serializers.py

from rest_framework import serializers
from .models import Todo


class TodoSerializer(serializers.ModelSerializer):
class Meta:
    model = Todo
    fields = ('id', 'title', 'description', 'completed')

This api call works inside react and I can get list of object and console output

http://127.0.0.1:8000/api/todos 
[
{
    "id": 14,
    "title": "First",
    "description": "first",
    "completed": false
},
{
    "id": 15,
    "title": "Second",
    "description": "second item",
    "completed": false
},
{
    "id": 16,
    "title": "Third",
    "description": "third item",
    "completed": false
}
]

http://127.0.0.1:8000/api/todos/14 doesn't work.

I have seen similar question, but I am able to make connection with localhost:3000 and get all the values here. it just for the detail object with id not showing up.

You're facing a CORS issue because your React client wants to access data from another server

You can see this topic where someone talks about using django-cors-headers with pip install django-cors-headers

Sorry, stack overflower, I have my api pointing to two urls. api/users and api/todos. I thought it was doable but, I got the error. Not really sure why, but it fixed my issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question How to fix ''http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.' ' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource React component has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS react Access to XMLHttpRequest has been blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource Cannot use GraphQL queries in React - has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource express react client XMLHttpRequest at from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM