允许CORS与瓶请求和响应
问题描述:
我想客户端通过Ajax请求的服务器连接。允许CORS与瓶请求和响应
我的客户,在本地主机上运行:8080,有一个按钮,调用,做一个简单的Ajax请求到本地运行的服务器,本地主机的功能:5000。
的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)
}
});}
(非常)简单的服务器,以瓶来实现,如下:
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 /航班/ origin_destination,它打印一条消息说它收到了来源和目的地。 然而,当我尝试做Ajax请求,我得到以下错误:
的XMLHttpRequest无法加载本地主机:5000 /航班/ Porto_Lisboa。协议方案仅支持跨源请求:http,data,chrome,chrome-extension,https。
如何纠正这种行为有什么建议? 预先感谢您
答
由于错误提示,你错过了你的请求,协议名称。尝试将它在字符串的开头添加:
const baseUrl = 'http://localhost:5000'
,而不是仅仅localhost:5000
你是正确的,我竟然发现,在同一时间通过谷歌搜索更多一些,现在我得到这个错误: XMLHttpRequest无法加载http:// localhost:5000 /次航班/ Porto_Lisboa。请求的资源上没有“Access-Control-Allow-Origin”标题。原因'http:// localhost:8080'因此不被允许访问。 现在 –
谷歌搜索它这是服务器任务添加'接入控制允许Origin'头,这样客户可以要求它。例如,如果您使用的是Flask,则可以查看https://flask-cors.readthedocs.io/en/latest/。 –
是的,这很正常。客户端拒绝读取请求,因为服务器没有使用“Access-Control-Allow-Origin”头来回答。 –