I am working on a simple DRF ReactJS app, but when I came across making a POST data from React app to the Django API, this error happens on the web console POST http://localhost:8000/api/project/create/ 400 (Bad Request)
and it says the problem is on my Create.jsx
This is my Create.jsx
file:
import React, { useState, useEffect} from 'react'
import { useNavigate } from 'react-router-dom'
import axios from 'axios'
const Create = () => {
const history = useNavigate()
const [title, setTitle] = useState("")
const [body, setBody] = useState("")
const createProject = async () => {
fetch('http://localhost:8000/api/project/create/', {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
title: JSON.stringify(title),
body: JSON.stringify(body),
})
console.log('title', title)
console.log('BODY', body)
}
return (
<div className="create-project">
<p>
<input type="text" onChange={e => setTitle(e.target.value)} value={title} ></input>
<textarea type="text" onChange={e => setBody(e.target.value)} value={body}></textarea>
<button onClick={createProject}>Submit</button>
</p>
</div>
)
}
export default Create
And this is the APIView in django: views.py
class CreateProject(CreateAPIView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
urls.py if needed:
path('project/create/', CreateProject.as_view(), name="create-project"),
CodePudding user response:
**change : **
headers: {
'Content-Type': 'application/json'
},
**To : **
headers: {
'Accept': 'application/json,
'Content-Type': 'application/json'
},
CodePudding user response:
i think your problem is cors
use cors header to can call endpoints