'Cors error with axios using authentication
I am having some trouble with axios once I add authentication.
My api.ts file:
import axios from "axios"
export default axios.create({
baseUrl: "https://someUrl"
})
In App.ts i am setting authentication header:
import api from api.ts
function App(){
api.default.header.common["Authorization"] = `Bearer ${token}`
}
And in my apiHooks.ts
import api from api.ts
import {useQuery} from "react-query"
const GetSomething = () => {
const {data, isLoading = useQuery("key", () => {
return api.get("/api")
});
return data?.data
};
export default GetSomething;
So when I'm using the hook, I get a Cors error ONLY when turning on authentication. The error is the following:
cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at "url"
Solution 1:[1]
Try putting "/" at the end of url. If it doesn't work, please comment.
import api from api.ts
import {useQuery} from "react-query"
const GetSomething = () => {
const {data, isLoading = useQuery("key", () => {
return api.get("/api/")
});
return data?.data
};
export default GetSomething;
Personally, I do it as follows
import axios from "axios";
const baseURL = "http://127.0.0.1:8080/api/";
// axios instance for making requests
export const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 5000,
headers: {
"Content-Type": "application/json",
accept: "application/json",
},
});
// request interceptor for adding token
axiosInstance.interceptors.request.use(
(config) => {
const token = localStorage.getItem("access");
if (token) {
config.headers["Authorization"] = "Bearer " + token;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
and hook:
import { useQuery } from "react-query";
import { axiosInstance } from "../utils/axios";
const fetchData = () => {
return axiosInstance.get("/item-list/");
};
export const useData = () => {
return useQuery("item-list", fetchData);
};
Solution 2:[2]
CORS has to be enabled on the server where the API is running on. CORS added new HTTP headers that allow servers to describe the set of origins that are permitted to read that information.
To enable CORS in Rails based application following code should be included in cors.rb-
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head],
expose: ['Access-Token', 'Uid', 'Client']
end
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | skelaw |
| Solution 2 | Muhammad Awais |
