【发布时间】:2021-06-24 01:18:25
【问题描述】:
我有一个使用 reactjs 构建的前端应用程序,django rest 框架用于使用 API 为该前端提供服务。 django rest API 工作正常,我通过 Postman 进行了检查。
当我向 http://127.0.0.1:8000/articles/ 发出 GET 请求时,我会得到文章列表,当我点击其中一篇文章时,它应该会将我带到 article detail page 以获取文章的特定 ID。这是通过向 http://127.0.0.1:8000/articles/id 发出 GET 请求来完成的。
问题是,当我对 id=2,3,4,5,... 发出 GET 请求时,它工作正常。但是当我尝试请求 id=1 时,我在 chrome 浏览器的控制台中收到以下错误
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)
因此,根本没有发出请求(我从服务器端验证)。我得到的只是上述错误。
请注意articles/2 或articles/3 等不存在此类错误。我已在 django settings.py 文件中允许相关主机。
这是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>
)
}
请帮我解决这个错误,通过调试我知道问题不在服务器端,GET 请求通过邮递员适用于 id=1。
【问题讨论】:
-
请用
id = 1添加请求的响应。 -
@ZunayedShahriar 我已经更新了这个问题。对于 id=1,根本没有提出请求。我收到上面指定的错误。如果我不允许 django 的 ALLOWED HOSTS 中的本地主机,则此错误与我将得到的错误相同,但事实并非如此。
-
您的服务器端可能存在路由冲突。而且,我不了解 django。
-
如果是这样,那我为什么要通过邮递员得到正确的json数据
-
这真的很奇怪。
标签: reactjs django django-rest-framework axios react-hooks