如何修复此axios GET请求?继续获取404状态代码

2024-09-19 23:33:49 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试将json数据传输到前端,并尝试了一系列版本的axios请求,但一直得到404状态码。你知道吗

这是前端格式的一个示例:

class App extends Component {
  constructor () {
    super();
    this.state = {
      message: ''
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick () {
    axios.get('./hello')
      .then(response => {
        this.setState({ message: response.data.text });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render () {
    return (
      <div className="button-container">
        <button className='button' onClick={this.handleClick}>Click Me</button>
        <p>{this.state.message}</p>
      </div>
    )
  }
}

和后端路由:

@app.route('/hello')
def hello_world():
   return jsonify(text='hello world')

错误消息说“加载资源失败:服务器响应状态为404(未找到)”或说http://localhost:5003/hello不存在


Tags: textdivmessagehelloworldreturnresponse状态
1条回答
网友
1楼 · 发布于 2024-09-19 23:33:49
  1. 首先检查你的服务器,哪个url和端口,你的api是公开的
  2. 您需要将完整的url传递给axios构造函数,否则它会将请求发送到您的客户端所在的同一源/url,例如localhost:3000的webapp。你知道吗

所以你的代码是

const SERVER_URL = 'http:localhost:5000'
axios.get(`${SERVER_URL}/hello`)

相关问题 更多 >