Vue3 app after logout throws CORS policy error - authentication

I have Vue3 app which makes requests with Axios. As I logout from the app and then login again app starts throwing error
create:1 Access to XMLHttpRequest at 'https://vue.tatrytec.eu/'
(redirected from 'https://tatrytec.eu/api/article/store') from origin
'https://vue.tatrytec.eu' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
One thing I dont understand is that as I reload the page it starts working and error is gone. The code is still the same. How can reload has impact to the CORS error?
The app code for Axios is in this Github repository.
import axios from "axios"
window.axios = axios;
//axios.defaults.baseURL = apiRoutes.API_URL_SHORT;
axios.defaults.withCredentials = true;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let authToken = localStorage.getItem('authToken');
axios.defaults.headers.common['Authorization'] = 'Bearer ' + authToken;
axios.defaults.headers.common['Access-Control-Allow-Origin'] = 'https://vue.tatrytec.eu';
Hope somebody knows cause I have no idea what happened there.

The problem was in the login form axios setting. There was this code
axios.defaults.headers.common = {
'Authorization': 'Bearer ' + token
};
I dont know where I found it but this garbage code rewrites whole common object in axios settings. So I lost all other headers. Really would like to know where I found this code. The proper style is to use array syntax like common['Authorization'] = ... Vrrrrr.

Related

Cross Origin Problem with Flask Api (Access-Control-Allow-Origin)

Hello all good people.
I have tested everything that I can find on internet and nothing is working to fix this problem. I'm really hoping that someone here can help me solve this.
When i try to do "patch" request from backend to my flask API I get this error (GET, DELETE & PUT are working fine):
Access to fetch at 'https://MYAPI-NOTREALURL.com' from origin
'https://MYBACKEND-NOTREALURL.com' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: The
'Access-Control-Allow-Origin' header contains multiple values
'https://MYBACKEND-NOTREALURL.com, *', but only one is allowed. Have
the server send the header with a valid value, or, if an opaque
response serves your needs, set the request's mode to 'no-cors' to
fetch the resource with CORS disabled.
This is how my code for API is written:
from flask_cors import CORS, cross_origin
from flask import render_template, redirect, flash, request, url_for, jsonify, session, make_response
from flask_restful import Api, Resource, reqparse
import requests
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
api = Api(app)
class ordersByID(Resource):
def get(self,ID_ORDER):
****
return jsonify(data)
def patch(self,ID_ORDER):
req321 = request.form
result = updateOrder(req321,ID_ORDER)
return result
def delete(self,ID_ORDER):
****
return result
def put(self,ID_ORDER):
****
return result
api.add_resource(ordersByID, "/orders/id/<string:ID_ORDER>")
if __name__ == '__main__':
app.run(debug=True)
I have tested everything that I can find on internet and nothing is working when trying to do patch request. I'm doing patch request with fetch from popup window.
<form action="{{ **https://MYAPI-NOTREALURL.com** }}" id="popupForm" method="patch" onsubmit="formFetch(event,this,'patch')">
You can check javascript code under.
function formFetch(e,form,method) {
result = fetch(form.action, {method:method, body: new FormData(form)})
.then(response => response.json())
.then(data => document.getElementById('submitedFormConfirmationText').innerHTML = data['DB_Result']
);
e.preventDefault();
document.getElementById('submitedFormConfirmation').style.display = 'inline';
};
I really hope that someone can help me solve this problem without needing to redo whole code?
I managed to solve this.
For some strange reason "patch" with small letters was working on local but when deployed it did not work.
Changing method from "patch" to "PATCH" solved this problem.

receive JSON array data from fetch or axios.get VueJS

I am going mental. So I have the code below. When I run it as is, I get
Access to XMLHttpRequest at 'URL' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If I remove the CORS header I get the same error. I am not sure what I am doing wrong. I will tell you if I curl the URL it works fine. What am I missing here.
Also, I have tried this using both axios.get AND fetch so I am open to both solutions.
getRoomUserCount: function () {
return axios
.get('URL', {
responseType: "json",
});
},
What it SHOULD return is an array of data, then using the code below I grab the array
mounted: function () {
this.roomUserCount = this.getRoomUserCount();
},
CORS policy is ALWAYS server related. You cannot change anything on your client-side to change that.
Enable CORS on your server to fix this.

Set-Cookie not accessible through axios or fetch

I am building a web application with a go backend and a vue.js frontend.
I want to do a simple sign in form in which I send the sign in request from a method of my component with Axios (or fetch) and get in response a JSON object of the user and a session token in the cookie to be stored and reused in future requests to the server.
The code of my components method :
class LoginComponent extends Vue {
sendLogin (): void {
axios.post<User>('http://192.168.1.227:8080/signin', body)
.then(res => console.log('Axios Response :', res)
.catch(err => console.error('Axios Error :', err))
}
}
The part of the code of the go server :
go API
with the headers :
go headers
the front and backend are on different IP addresses in a local network and they communicate through HTTP.
The problem that I faced is that when receiving the response after the post request to login I don't have access to the cookie that has been set by the server. When I use Axios to analyze the response the cookie isn't in the headers whereas when I look at the network logs in the browser, the cookie is in the headers but it is not saved and it is not sent when I do another request.
Also, the only header that is visible with Axios is Content-Type : application/json; charset=UTF-8
I tried many things to be able to see this cookie but it doesn't work :
adding { withCredentials: true } to the axios request or axios.defaults.withCredentials = true to the axios instance only stops the request because of CORS.
changing all the Access-Control headers to "*" didn't change anything
using { auth: { username: 'foo', password: 'bar' } } in the axios options instead of the body
The only thing that worked and automatically saved the cookie was to send the request via the attributes of the form html tag, like so :
<form method="POST" action="http://192.168.1.227/signin">
...
</form>
But this way I am redirected to the JSON response object and not to one of my routes from vue-router and I can't access the User object in my app.
Is there any way that my problem can be solved?
Ok so the comment of Зелёный was the answer.
I needed the go server to set Access-Control-Allow-Origin: http://192.168.1.218:8080 (the address of the frontend) and then configure axios with { withCredentials: true } to be able to automatically store the cookie. Although I still don't see it when I do a console.log on the axios response, it is successfully stored and reused for each call to the server.

Vue.js - CORS error in local and production

I have got a file that's name is request.js,
import axios from 'axios'
const baseURL = 'https://SOME_URL.com/api/'
const config = {
baseURL,
timeout: 10000,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
}
}
const request = axios.create(config)
export default request
and I'm trying to send request in Vuex Actions;
import request from '../request'
const actions = {
postData(_, payload){
return request.post('a-request-url', payload)
}
}
Sending 2 requests and throws a CORS error when I run request. CORS error Access to XMLHttpRequest at 'https://crm.clinic/api/crm/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
AND 2 requests like;
and the real problem, cors error continious when deploy my code as production. Can you help me?
If you read the second part in the error it says where the issue is.
Request header field access-control-allow-origin is not allowed by
Access-Control-Allow-Headers in preflight response
As you can see you need to allow access in preflight response. A preflight request is something the browser does before sending your actual GET/POST/etc request. In the devtools' network tab you have 2 requests for the /login url. First one is a preflight using OPTIONS method.
To fix the issue you need to make sure your backend server returns 'Access-Control-Allow-Origin': 'http://localhost:8080' header in it's response for OPTIONS requests. Currently it is specifying only allowed methods and headers. You don't need to add those headers to your axios request.

Sending axios get request with authorization header

I have tried to send axios get request using vue.js and it worked just fine when there was no need to send headers. However, when it was required to send an authorization jwt, i was getting CORS error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." I don't know why is this problem occurring since there is Access-Control-Allow-Origin: '*' header in the response. My code is the following:
axios.get(url, {
headers: {
'Authorization': 'Bearer TOKEN'
}
})
.then(function (response) {
console.log(response.data)
})
The weirdest thing is when I use querystring.stringify or JSON.stringify on the header, I don't get the error 403(forbidden), but just an error 401 - Unauthorized. I tried with variable and with the token itself and it didn't work.
I tried to send a post request in order to get a web token with required data - username an password and it worked. I was able to get the token.
I made a whole bunch of research the last two days on this and I found different kind of request structure and configs which I tried all of them, but none were efficient. Is there a way to check if the request is being send with the header? Is something else the problem? If someone can help, I would appreciate. Thanks.
I think you should add this code to the bootstrap.js (or where the axios is defined):
window.axios = require('axios'); // I think its already added
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest'
};
You didn't mention, but I guess you use laravel, or other framework, what is protected from csrf attack, thats why you need to add the generated token to your ajax request header.