AlixL
AlixL

Reputation: 372

Share auth between django and react

I have a website with the default django authentication system. The whole website is static and I would like to have a couple pages dynamic using React app as frontend.

I expect these dynamic pages to make a some http requests to the django server. My understanding is that I can use axios on the frontend and deal with the requests on the backend with Django Rest Framework.

I think the current authentication system works fine, how can I make axios requests to DRF using the existing user's session ?

Upvotes: 0

Views: 906

Answers (2)

Shamar Yarde
Shamar Yarde

Reputation: 761

Once the user logs in, get the token from the backend using the following:

axios.post(`http://localhost:${port_number}/${urlpattern}`, {
     headers: {
    'Content-Type': 'application/json',
    data: {
      username,
      password
})
   .then(response => {
      console.log(`token: ${response.token}`);
   })

Port number could be 8000 and url pattern could be /api/auth/login for example. This answer mostly comes from the last reference.

References

Youtube. Full Stack React & Django [1] - Basic REST API. https://www.youtube.com/watch?v=Uyei2iDA4Hs. (Accessed 23 April, 2021).

Youtube. Full Stack React & Django [2] - Implementing React. https://www.youtube.com/watch?v=GieYIzvdt2U. (Accessed 23 April, 2021).

Youtube. Full Stack React & Django [3] - Redux & HTTP. https://www.youtube.com/watch?v=BmL8iaLMnQ0. (Accessed 23 April, 2021).

Youtube. Full Stack React & Django [4] - Error Handling & Alerts. https://www.youtube.a/watch?v=Fia-GGgHpK0. (Accessed 23 April, 2021).

Youtube. Full Stack React & Django [5] - Django Token Authentication. https://www.youtube.com/watch?v=0d7cIfiydAc. (Accessed 23 April, 2021).

Youtube. Full Stack React & Django [6] - Auth State & Private Routes. https://www.youtube.com/watch?v=EmAc4wQikwY. (Accessed 23 April, 2021).

Upvotes: 1

Gabriel Espinosa
Gabriel Espinosa

Reputation: 38

If you already build your urls.py file and have the endpoints working fine, you can start the django server using your ip address/port and in axios just replace the url. like this.

  axios({
  method: 'post',
  url: `http://${IP_ADRESS}:8000/api/auth/login`,
  headers: {'Content-Type': 'application/json'},
  data: {
    username,
    password,
  },
})

dont forget to set your IP adress in ALLOWED_HOST in settings.py

ALLOWED_HOSTS = ['IP_ADDRESS']

Upvotes: 0

Related Questions