Access to Xmlhttprequest has been blocked by CORS policy

Asked

Viewed 53,582 times

3

I have two Flask applications running locally on my machine. One is running on port 5000 and the other on port 5050. I need to make a 5000 app call to 5050. But I’m having this problem:

Access to XMLHttpRequest at 'http://localhost:5050/run' from origin 'http://127.0.0.1:5000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The call even occurs in the application running on port 5050, but the data is not passed and ends up giving a INTERNAL SERVER ERROR in the 5050.

This is the code that makes the call:

$.post('http://localhost:5050/run', {
  id: 'test',
  command: 'echo michael'
}, function (data) {
  console.log(data)
});

This is application code 5050:

import logging

from flask import Flask, json
from flask import request
from flask_cors import CORS

from task_executor import execute_task

app = Flask(__name__)
cors = CORS(app)
logging.getLogger('flask_cors').level = logging.DEBUG


@app.route('/check', methods=['GET'])
def hello():
    response = app.response_class(
        response="Server is running!",
        status=200,
        mimetype='text/plain',
    )
    return response


@app.route('/run', methods=['POST'])
def post():
    task_info = request.get_json()
    print(task_info)
    task_output = execute_task(task_info)
    response = app.response_class(
        response=json.dumps(task_output),
        status=200,
        mimetype='application/json'
    )
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response


if __name__ == '__main__':
    app.run(debug=True, host='localhost', port=5050)

I’ve researched this error on google and even on the stack overflow itself, but none of the solutions worked for me.

Here are some links I searched:

  1. https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present
  2. No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'null' is therefore not allowed access. - Phonegap
  3. https://flask-cors.readthedocs.io/en/latest/
  4. https://stackoverflow.com/questions/30717152/python-flask-how-to-set-response-header-for-all-responses

Note: I don’t want to have to use any extensions or run the browser with some flag!


EDIT:

The following code gives error 400 (BAD REQUEST)

$.ajax('http://127.0.0.1:5050/run', {
  contentType: 'application/json',
  crossDomain: true,
  data: {id: 'test', command: 'echo hello'},
  method: 'POST'
})
  • Dear Micheal just understand what the error says, the address http://localhost:5050 is different from http://127.0.0.1:5000, logo cannot access directly via Ajax pq this would imply security failure, the only way to allow access is in Flask that running port 5050 add the HEADER, example: https://gist.github.com/brcontainer/21956e354c64d514402f13e49c9913c1. . I recommend you read https://answall.com/a/145493/3635 to understand what this error means. If you have further questions you can comment here.

  • I already did that. I changed the question with the application code. It doesn’t work yet.

  • Then but the translated message of No 'Access-Control-Allow-Origin' header is present on the requested resource. states Access-Control-Allow-Origin header não esta presente no recurso requisitado, either you haven’t restarted Flask, or you’ve confused something. Try to restart Flask and run the address http://127.0.0.1:5000 in a private window. Try the shape of the code I sent you as well

  • Dear Micheal, remove the crossDomain: true for error 400 (I believe this is the problem)

  • The way you sent me: NameError: name 'headers' is not defined

  • But you have to import the Flask LIB from the header, if not the method won’t even exist. How long have you been working with Flask?

  • I have tried to import but Pycharm does not show an option to import this symbol with flask. And error 400 continues even without the crossDomain: true. I used very little flask. Only for routing msm urls.

  • 1

    Must be the content-type, Flask must be rejecting, because the route is not written to receive such information, I will create the flask environment here and send you a feedback

  • Ahh! I’m getting the requisition right with Postman

  • 2

    Dear Micheal, Postman is not a web page, so there are no security problems and so it will not cause crashes and blocks

Show 5 more comments

2 answers

6


I found the answer. It was simply because the field data was a javascript object. In documentation says that data can be a PlainObject or String or Array, so I don’t know why it didn’t work.

That code is working:

$.ajax({
    url: 'http://localhost:5050/run',
    contentType: 'application/json',
    cache: false,
    method: 'POST',
    dataType: 'json',
    data: JSON.stringify({
        id: 'test',
        command: 'echo michael'
    }),
    success: function(data) {
        console.log(data);
    }
});

-3

On the side of my server that is running on port 8080, I used in the controller the following annotation with Spring:

@Requestmapping("/categories")

@Crossorigin(Origins = "http://localhost:8100")

public class Categoriacontroller {...}

"import org.springframework.web.bind.Annotation.*;"

Because my front is running on port 8100 (Ionic) so it worked here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.