网络错误:Django后端到React前端

3
我正在尝试使用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;
1个回答

2

我需要在我的Django API上设置CORS。问题不在于我的前端,而是后端没有正确设置。每当您从不同的服务器发出API请求时,您都必须在后端上设置CORS。


提供代码示例,老兄。 - B-Tron of the Autobots

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接