Mehdi
Mehdi

Reputation: 160

Cors not allowed while using Axios

Hey I was working with fetch a normal fetch to request my API in my server, and It was working, but I found out that Axios is easier, so I tried to replace every fetch, but it looks like xhr doesn't work because of cors,

I already allowed cors when I was working with fetch, but for some reason cors is not allowed for xhr (Axios) requests

here is Axios defaults:

import axios from "axios"
import store from "@/store"
import { getLocalStorage } from "@/services/functions.services.js"

axios.defaults.baseURL = store.getters.getData("serverLink")
axios.defaults.withCredentials = true

axios.defaults.headers.common["Authorization"] = `Bearer ${getLocalStorage("access_token")} ${getLocalStorage("refresh_token")}`

and here is how I use Axios:

function fetchF(link, body, method) {
    return new Promise(async (resolve, reject) => {
        axios[method.toLowerCase()](link, body)
            .then(rsp => {
                setLocalStorage("access_token", rsp.access_token);
                setLocalStorage("refresh_token", rsp.refresh_token);
                resolve(rsp);
            }).catch(error => {
                setLocalStorage("access_token", "");
                setLocalStorage("refresh_token", "");
                store.dispatch("changeData", {
                    option: "alertEl",
                    value: "Please log in, and try again",
                });
                return resolve({ isSuccess: false, err: "Please log in, and try again" });
            })
    });
}

and here is how I enabled cors on the server-side:

app.use(cors({
    credentials: true,
}));

here is the error: error in the network page

Upvotes: 2

Views: 14482

Answers (3)

ikhvjs
ikhvjs

Reputation: 5947

If a browser sends a CORS request with credentials: true, the browser will not accept a response with 'Access-Control-Allow-Origin:*. You must sepecify Access-Control-Allow-Origin to one domain. Such as Access-Control-Allow-Origin:example.com.

Ref. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#requests_with_credentials

Upvotes: 2

Mehdi
Mehdi

Reputation: 160

Just to clarify how to change the Access-Control-Allow-Origin to a specific domain (@Cypherjac)

here is how:

app.use(cors({
    origin: "http://localhost:8080",
    credentials: true,
}));

Upvotes: 0

Cypherjac
Cypherjac

Reputation: 879

This is an error with your server, because for every request, a preflight request is sent before the actual one..

And from the error 'PreflightWildcardOriginNotAllowed' basically means that in your server configurations you have the list of domains set to the wildcard '*'

So just change your cors options in the server for 'Access-Control-Allow-Origin' to your domain instead of '*'

And if your server has it's own way of handling preflight requests, which are basically requests sent with 'OPTIONS', you can set the domains handled by that to your domain

Upvotes: 1

Related Questions