I have a frontend application built using reactjs and django rest framework is used to serve this frontend using APIs. The django rest APIs are working fine, I have checked via Postman.
When I make a GET request to http://127.0.0.1:8000/articles/
, I get the list of articles, and when I click on one of them, it is supposed to take me to the article detail page
for that specific id of the article. This is done by making a GET request to http://127.0.0.1:8000/articles/id
.
The problem is, when I make GET request for id=2,3,4,5,... , it works fine. But when I try to make a request for id=1, I get the following error at console of chrome browser
Access to XMLHttpRequest at 'http://127.0.0.1:8000/articles/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)
So, the request is not made at all(I verified from server side). All I get is the above error.
Please note that there is no such error for articles/2
or articles/3
and so on. I have allowed the relevant host in django settings.py
file.
This is the code I have for the article detail page
.
function ArticlePage(props) {
const [MainArticle, setMainArticle] = useState({});
const {id} = useParams()
const url = 'http://127.0.0.1:8000/articles/'+id;
useEffect(() => {
console.log("hello world");
axios.get(url)
.then((response) => {
setMainArticle(response.data);
console.log(response.data);
})
.catch((error)=>console.log(error))
}, [url]);
return (
<section className="postsBody">
<Article
title={MainArticle.title}
author={MainArticle.author}
timestamp={MainArticle.timestamp}
content={MainArticle.content}
/>
</section>
)
}
Please help me out with this error, via debugging I came to know that the problem is not in the server side, the GET request works for id=1 via postman.