2017-08-25 131 views
-3

我想客戶端通過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。

如何糾正這種行爲有什麼建議? 預先感謝您

回答

0

由於錯誤提示,你錯​​過了你的請求,協議名稱。嘗試將它在字符串的開頭添加:

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

,而不是僅僅localhost:5000

+0

你是正確的,我竟然發現,在同一時間通過谷歌搜索更多一些,現在我得到這個錯誤: XMLHttpRequest無法加載http:// localhost:5000 /次航班/ Porto_Lisboa。請求的資源上沒有「Access-Control-Allow-Origin」標題。原因'http:// localhost:8080'因此不被允許訪問。 現在 –

+0

谷歌搜索它這是服務器任務添加'接入控制允許Origin'頭,這樣客戶可以要求它。例如,如果您使用的是Flask,則可以查看https://flask-cors.readthedocs.io/en/latest/。 –

+0

是的,這很正常。客戶端拒絕讀取請求,因爲服務器沒有使用「Access-Control-Allow-Origin」頭來回答。 –