A
A
authoraytee2022-02-09 14:22:03
Django
authoraytee, 2022-02-09 14:22:03

How to set up routes in Django + React?

I can't set up the routes correctly More

specifically:
Now it works so that along the path there is localhost:8000/api/ api is passed in json format,
and along the path localhost:3000/ - frontend on react, so everything works correctly

BUT

I want to do this so that the api works along the path localhost:8000/api/todos/ , and the front on localhost:3000/todos/ , but I can’t do it at all, I don’t understand.

Maybe this is done very simply, tell me, please!

Here is my code:
config - settings folder, main folder django
todos - app
frontend - react folder

config/urls.py:

from django.contrib import admin
from django.urls import include, path # new

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('todos.urls')), # new
]


todos/urls.py:
from django.urls import path
from .views import ListTodo, DetailTodo

urlpatterns = [
  path('<int:pk>/', DetailTodo.as_view()),
  path('', ListTodo.as_view()),
]


todos/models.py:
from django.db import models

class Todo(models.Model):
  title = models.CharField(max_length=200)
  body = models.TextField()
  
  def __str__(self):
    return self.title


todos/views.py
from rest_framework import generics
from .models import Todo
from .serializers import TodoSerializer

class ListTodo(generics.ListAPIView):
  queryset = Todo.objects.all()
  serializer_class = TodoSerializer

class DetailTodo(generics.RetrieveAPIView):
  queryset = Todo.objects.all()
  serializer_class = TodoSerializer


todos/serializers.py:
from rest_framework import serializers
from .models import Todo

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


fronteds/src/App.js:
import React, { Component } from 'react';
import axios from 'axios'; 

class App extends Component {
    state = {
      todos: []
    };

    componentDidMount() {
      this.getTodos();
    }

    getTodos() {
      axios
        .get('http://127.0.0.1:8000/api/')
        .then(res => {
          this.setState({todos: res.data });
        })
        .catch(err => {
            console.log(err);
        });
    }

    render() {
        return ( 
            <div> 
              {this.state.todos.map(item => ( 
                  <div key = {item.id}>
                      <h1>{item.title}</h1> 
                      <span>{item.body}</span>
                  </div>
              ))} 
            </div>
        );
    }
}

export default App;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
authoraytee, 2022-02-09
@authoraytee

I managed to fix it, I decided this: I
changed the path to api to localhost:8000/api/todos/
In App.js I changed the path to api like this: I added routes to index.js :
.get('http://127.0.0.1:8000/api/todos/')

import React from 'react';
import ReactDOM from 'react-dom';
import {
    BrowserRouter as Router,
    Routes,
    Route
} from "react-router-dom";
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
    
const Routing = () => {
      return(
        <Router>
          <Routes>
            <Route exact path="todos/"  element={<App />} />
          </Routes>
        </Router>
      )
}
    
ReactDOM.render(
      <React.StrictMode>
        <Routing />
      </React.StrictMode>,
      document.getElementById('root')
);
reportWebVitals();

D
Dr. Bacon, 2022-02-09
@bacon

I want to make the api work on the path localhost:8000/api/todos/
well, you yourself included it as /api/ in config/urls.py, change it and connect it as you need, in React it’s most likely the same

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question