首页 > 解决方案 > 在 ReactJS 中获取 onComponentDidMount 期间出现 CORS 错误

问题描述

在 reactjs 中获取 api 数据时,我得到空页面作为输出。

回购:https ://github.com/te3t0/building-small-blog

我可能是 reactjs 的新手,即使数据被完美地获取,我也会得到一个空页面。如果有人能在我做错的地方帮助我,那就太好了。非常感谢你。

endpoint_url : http://localhost:8000/api/blog_list

api数据:

[
    {
        "id": 1,
        "url": "http://localhost:8000/api/blog_detail/brown",
        "title": "brown",
        "slug": "brown",
        "image": "http://localhost:8000/media/blog/image_2.jpg",
        "description": "",
        "created_on": "2020-05-08T15:20:53Z",
        "status": true,
        "category": [
            1
        ]
    },
    {
        "id": 2,
        "url": "http://localhost:8000/api/blog_detail/black",
        "title": "black",
        "slug": "black",
        "image": "http://localhost:8000/media/blog/loc.png",
        "description": "",
        "created_on": "2020-05-08T17:14:31Z",
        "status": true,
        "category": [
            2
        ]
    }
]

./src/Base.js

export default class App extends Component{

  state = {
    bloglist:[]
  };

  componentDidMount(){
    this.fetchData()
  }

  fetchData = async () => {
    try{
      const response = await fetch("http://localhost:8000/api/blog_list");
      const jsonResponse = await response.json()
      this.setState({bloglist:jsonResponse})
    }
    catch(error){
      console.log(error)
    }
  }

  render(){
    const {bloglist} = this.state
    if(!bloglist){
      return (
        <div>
          <h1>loading...</h1>
        </div>
      )
    }

    return (
      {
        bloglist.map(bloglist => (
          <h3 class="mb-2">
            <a href="single.html">{bloglist.title}</a>
          </h3>
          <p class="mb-4">{bloglist.description}</p>
          ))
      }
    )
  }
}

标签: javascriptdjangoreactjs

解决方案


由于这是您的第一篇文章 - 在调试问题方面有些事情并不顺利。

对于像您提出的问题这样的较大问题 - 它有助于从开发人员控制台工具以及远程存储库源中提供错误。

例如

GET http://localhost:8000/api/blog_list net::ERR_FAILED

'http://localhost:8000/api/blog_list' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

从那里 - 通过包含远程存储库- 我能够通过How can I enable CORS on Django REST Framework了解更多信息

这导致了以下答案:

  1. pip install django-cors-headers

  2. 添加已安装的应用程序

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)
  1. 添加中间件
MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',  
    'django.middleware.common.CommonMiddleware',  
    ...
)

CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
    'http://localhost:3000',
]

推荐阅读