Home > Software design >  Problems sending GET http requests from localhost:5000 to localhost:8000
Problems sending GET http requests from localhost:5000 to localhost:8000

Time:11-16

I have a backend cython flask app, which has a GET endpoint with route http://127.0.0.1:8000/items. My second app is a html website hosted at http://127.0.0.1:5000. And I'm trying to send a request from my website to said endpoint.

Flask app:

@app.route('/items', methods=["GET"])
def getPrices():
    .......
    # "stuff" is a list with json objects [{"x": "y"}, {"x": "z"}, ....]
    return {
        "items": stuff
    }

Im trying to fetch it like this:

let response = await fetch(
   'http://127.0.0.1:8000/items',
   {
      method: 'GET',
      mode: 'no-cors' // if i don't do this im getting fetch blocked by cors error
});
console.log(response);

However this is the response I'm getting

Response {type: 'opaque', url: '', redirected: false, status: 0, ok: false, …}
body: null
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
[[Prototype]]: Response

When i go to http://127.0.0.1:8000/items in my browser the endpoint works fine. Can anybody please help me with this?

CodePudding user response:

mode: no-cors in your Flask endpoint is being used incorrectly here and will lead to responses of type: "opaque" which have unreadable bodies. Explained here.

Browsers don't allow cross-origin requests to work unless servers explicitly allow them.

One way of resolving this is to use flask-cors (can be installed via pip), example below:

from flask import Flask
from flask-cors import CORS, cross_origin

app = Flask(__name__)

cors = CORS(app)
# or, if you want some specific (or any) route to allow
# any cross-origin request
cors = CORS(app, resources={r"/some-route/*": {"origins": "*"}})

@app.route("/")
# this decorator is only necessary if the origin wasn't set earlier
@cross_origin()
def my_api():
  return "This request works cross-origin!"
  • Related