【问题标题】:allowing CORS request with Flask and React允许使用 Flask 和 React 请求 CORS
【发布时间】:2018-02-03 18:46:50
【问题描述】:

我正在尝试通过ajax 请求将客户端与服务器连接。

localhost:8080 上运行的我的客户端有一个按钮,该按钮调用一个函数,该函数向本地运行的服务器localhost:5000 发出简单的ajax 请求。

onClick 函数:

  handleClick() {
console.log("check flights button was clicked!");
console.log(this.state);
const baseUrl = 'localhost:5000'
ajax.get(`${baseUrl}/flights/${this.state.origin}_${this.state.destination}`)
.end((error, response) => {
  if (!error && response) {
    console.log('got a valid response from the server')
  } else {
    console.log(`Error fetching data from the server: `, error)
  }
});}

使用Flask 实现的(非常)简单的服务器如下:

from flask import Flask, request
from flask_restful import Resource, Api
from json import dumps

app = Flask(__name__)
api = Api(app)

class Flights(Resource):
    def get(self, origin, destination):
    answer = 'we got some data ' + origin + ' ' + destination
    print answer

api.add_resource(Flights, '/flights/<string:origin>_<string:destination>')

if __name__ == '__main__':
    app.run()

如果我只需转到localhost:5000/flights/origin_destination,我就可以访问服务器,它会打印一条消息,说明它已收到来源和目的地。 但是,当我尝试执行 ajax 请求时,我收到以下错误:

XMLHttpRequest cannot load localhost:5000/flights/Porto_Lisboa. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

关于如何纠正这种行为的任何建议? 提前谢谢你。

【问题讨论】:

    标签: python reactjs flask cors


    【解决方案1】:

    正如错误提示的那样,您的请求中缺少协议名称。尝试将其添加到字符串的开头:

    const baseUrl = 'http://localhost:5000'
    

    而不仅仅是localhost:5000

    【讨论】:

    • 你是对的,我实际上是同时通过谷歌搜索发现的,现在我得到这个错误:XMLHttpRequest 无法加载localhost:5000/flights/Porto_Lisboa。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'localhost:8080' 不允许访问。立即谷歌搜索
    • 添加Access-Control-Allow-Origin 标头以便客户端可以请求它是服务器任务。如果你正在使用 Flask,你可以看看 flask-cors.readthedocs.io/en/latest 例如。
    • 是的,这很正常。客户端拒绝读取请求,因为服务器未使用 Access-Control-Allow-Origin 标头进行响应。
    • 感谢您的回答,他们非常有帮助!
    • 嗨@RafaelMarques,如果这个或任何答案已经解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
    猜你喜欢
    • 2020-05-25
    • 2020-11-16
    • 2023-03-10
    • 2018-07-28
    • 1970-01-01
    • 2017-07-28
    • 2015-03-09
    • 2016-09-15
    • 2019-07-02
    相关资源
    最近更新 更多