【发布时间】: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.
关于如何纠正这种行为的任何建议? 提前谢谢你。
【问题讨论】: