2

I'm building the front-end of a personal project with vue.js. My back-end is a rest API in flask (flask-restful). First I had problems with cors when trying to do GET requests, that was solved using the following code:

# file  __init__.py
from flask_cors import CORS, cross_origin

    app = Flask(__name__)
    CORS(app)

But I still getting this error when I'm doing a POST request (login):

Access to XMLHttpRequest at 'http://127.0.0.1:5000/api/auth/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

In the API I'm using Resource objects from flask-restful, this is my Login view:

class LoginApi(Resource):
    def post(self):
        try:
            data = request.get_json(force=True) 
            user = User.objects.get(email=data.get('email'))
            authorized = user.check_password(data.get('password'))
            if not authorized:
                return {'error': 'Email or password invalid'}, 401
        
            expires = datetime.timedelta(days=7)
            access_token = create_access_token(identity=str(user.id), expires_delta=expires)
            return {'token': access_token}, 200
        except (UnauthorizedError, DoesNotExist):
            raise UnauthorizedError
        except Exception:
            raise InternalServerError

To make the request I'm using vue-resource. My configuration:

    // main.js
    import VueResource from 'vue-resource'

    Vue.use(VueResource)
    Vue.http.options.root = process.env.API_URL ? process.env.API_URL : 'http://127.0.0.1:5000/';

My method:

save () {
            this.service = new UserService(this.$resource)

            this.service
                .login(this.user)
                .then(res => console.log(res), error => console.log(error))
        }

The UserService class:

export default class UserService {
    constructor(resource) { // resource comes from VueResource
        this._resource = resource("api/auth/login")
    }

    login (user) {
        return this._resource
            .save(user)
    }
}

I appreciate any kind of help. It's been some hours I'm getting this error, and I'm not getting anywhere. I saw a lot of similar questions but none of them applied to my case so far.

Wiliane Souza
  • 307
  • 2
  • 9
  • Your code looks fine. `CORS(app)` should work for all routes. Can you try with [@cross_origin()](https://flask-cors.readthedocs.io/en/latest/#route-specific-cors-via-decorator) at specific route level and see if it works? – Ajeet Shah Feb 24 '21 at 22:28
  • Importing and adding @cross_origin() to the login route didn't make any difference :/ – Wiliane Souza Feb 26 '21 at 18:41
  • 1
    CORS errors are related to backend, so, this problem should not be in vuejs code, but should be in flask code. Right? (Assuming you are able to use flask rest end points using Postman). Can you share your minimal flask code in which the problem exists? – Ajeet Shah Feb 26 '21 at 19:01
  • 1
    Hey, thanks for your help. I was trying to figure out what was wrong with the cors config in the backend, and at some point it started working, so I started taking of the configuration pieces to see what made it work. I took everything out. So my code it's the same, but for some reason, now it is working lol – Wiliane Souza Mar 02 '21 at 17:57
  • 1
    Yes. CORS issues sometimes are really hard to debug. Glad that you have fixed. Here is how I solve my cors issues: First, I write configurations (i.e. adding response headers); if it still doesn't work, I just recheck and restart backend service. After few hours or some time, it starts working automatically. I agree, cors are really time-consuming thing in the world :D. And, on Stackoverflow, people always eventually fix it by themselves. We just keep motivating (provide debugging methods) them. :) – Ajeet Shah Mar 02 '21 at 18:05
  • Encounter a similar issue. Both the host and api is 127.0.0.1:5000 but CORS error pop up. However, if I change the access point to localhost:5000, it works fine. – Jim LK Yu Mar 13 '23 at 03:00

0 Answers0