Rafael Marques
Rafael Marques

Reputation: 1445

allowing CORS request with Flask and React

I am trying to connect a client with a server via ajax requests.

My client, running on localhost:8080, has a button which invokes a function that does a simple ajax request to a locally running server, localhost:5000.

onClick function:

  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)
  }
});}

the (very) simple server, implemented with Flask, is as follows:

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()

I can access the server if i simply go to localhost:5000/flights/origin_destination, which prints a message saying it received the origin and destination. However, when I try to do the ajax request, I get the following error:

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

Any suggestions on how to correct this behaviour? Thank you in advance.

Upvotes: 1

Views: 11567

Answers (1)

Kewin Dousse
Kewin Dousse

Reputation: 4027

As the error suggest, you're missing the protocol name in your request. Try to add it at the start of the string :

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

instead of just localhost:5000

Upvotes: 5

Related Questions