1

I have created an Api using django rest framework (localhost/users/profile) that gets the user's details if they are logged in. It works perfectly when I call the API in the backend when user is logged in the backend.

enter image description here

But when I try to access the same API from my React front end, it doesnt work.

I think the problem would be that cookies are not stored when a request is made from the backend. But I dont know how to solve it.

import React, { useEffect, useState } from "react"
import AuthContext from '../context/AuthContext'
import {Link} from 'react-router-dom'

const ProfilePage = () => {
    const [profiles, setProfiles] = useState([])
  
    const fetchData = async () => {
      const response = await fetch("http://127.0.0.1:8000/users/profile")
      const data = await response.json()
      setProfiles(data)
      console.log(data)
    }

  
    useEffect(() => {
      fetchData()
    }, [])
    
  
    return (
      <div>
        {profiles.length > 0 && (
          <ul>
            {profiles.map(profile => (
              <li key={profile.id}>{profile.name}</li>
            ))}
          </ul>
        )}
      </div>
    )
  }
  

export default ProfilePage

error from console enter image description here

error from Backend server enter image description here

  • Does this answer your question? [Fetch API with Cookie](https://stackoverflow.com/questions/34558264/fetch-api-with-cookie) Note you have to use `credentials: 'include'` as mentioned by [this answer](https://stackoverflow.com/a/38935838/14991864). Also note that you will have to configure CORS on your backend. – Abdul Aziz Barkat Jul 15 '22 at 04:09
  • I have configured cors on my backend and login, register and logout apis are working. I am storing access and refresh token in local storage. But I dont understand why profile API is not working from front end. – Khal Shaphat Jul 15 '22 at 04:15
  • Did you read the duplicate my comment links to? `fetch` does not send any cookies to another domain unless you explicitly specify `credentials: 'include'`. That is the issue, Django manages the authentication, etc. through the cookies. If the cookies don't persist across calls, you really aren't logged in. – Abdul Aziz Barkat Jul 15 '22 at 04:19
  • I have added credentials:'include' to the login fetch. But I still get the same error – Khal Shaphat Jul 15 '22 at 04:25
  • "_added credentials:'include' to the login fetch_" you need to add that to **all** your `fetch` calls. – Abdul Aziz Barkat Jul 15 '22 at 04:26
  • I have, but nothing has changed – Khal Shaphat Jul 15 '22 at 04:39

0 Answers0