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.