Answer the question
In order to leave comments, you need to log in
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
]
from django.urls import path
from .views import ListTodo, DetailTodo
urlpatterns = [
path('<int:pk>/', DetailTodo.as_view()),
path('', ListTodo.as_view()),
]
from django.db import models
class Todo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
def __str__(self):
return self.title
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
from rest_framework import serializers
from .models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = ('id', 'title', 'body',)
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
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();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question