0
votes

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.

2
Your MIDDLEWARE has 2 CommonMiddleWare. Let's fix that first. Move 'corsheaders.middleware.CorsMiddleware' to after 'django.contrib.sessions.middleware.SessionMiddleware'. Remove the last element of MIDDLEWARE. Also add corsheaders to INSTALLED_APPS.Melvyn
@Melvyn Thanks for you response, I have made changes and issues is still persistent.Ajay GC

2 Answers

0
votes

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

0
votes

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.