【问题标题】:Network Error Django Backend to React Frontend网络错误 Django 后端反应前端
【发布时间】:2018-11-09 18:30:04
【问题描述】:

我正在尝试使用 axios 将我的 Django 后端连接到 React 前端以访问 api 端点。我已经使用 curl 测试了 api,看看我是否收到了测试数据的 json,这很好。我已经打开了端点,因此它不需要身份验证。但我不断在我的 javascript 控制台中收到此错误:

编辑:表示我正在我的计算机上运行 api 和前端

Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)

Test.js- 测试组件以测试将后端反馈到前端。我想控制台记录数据,但只捕获错误。

import React, {Component} from 'react'
import axios from 'axios';

class Test extends Component{
  constructor(){
    super();
    this.state = {
      messages:[],
    }
  }
  componentDidMount(){
    axios.get('http://127.0.0.1:8000/api/message/?format=json')
      .then(res=> {
        console.log(res);
      })
      .catch(error =>{
        console.log(error);
      });
}
  render(){
    return(
      <div>
        <h1>
          Message:
        </h1>
      </div>
    )
  }
}


export default Test;

【问题讨论】:

    标签: reactjs django-rest-framework axios


    【解决方案1】:

    我需要在我的 django api 上设置 CORS。问题不在于我的前端,而是后端设置不正确。每当您有来自不同服务器的 api 请求时,您都必须在后端设置 CORS。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-28
      • 2022-11-07
      • 2020-02-13
      • 2021-06-18
      • 2021-10-22
      • 2015-03-23
      • 2020-03-09
      相关资源
      最近更新 更多