Question

[Solved] Vue Axios CORS policy: No ‘Access-Control-Allow-Origin’

I build an app use vue and codeigniter, but I have a problem when I try to get api, I got this error on console

Access to XMLHttpRequest at 'http://localhost:8888/project/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.

I have been try like this on front-end (main.js)

axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

and this on backend (controller)

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

and vue login method

this.axios.post('http://localhost:8888/project/login', this.data, {
   headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "GET, POST, PATCH, PUT, DELETE, OPTIONS",
          "Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token"
        }
      }).then(res => {
        console.log(res);
      }).catch(err => {
        console.log(err.response);
      });

I’ve searched and tried in stackoverflow but does not work, how I can solve it? thank you so much for your help

Enquirer: Ashtav

||

Solution #1:

CORS is the server telling the client what kind of HTTP requests the client is allowed to make. Anytime you see a Access-Control-Allow-* header, those should be sent by the server, NOT the client. The server is “allowing” the client to send certain headers. It doesn’t make sense for the client to give itself permission. So remove these headers from your frontend code.

axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

this.axios.post('http://localhost:8888/project/login', this.data, {
   headers: {
          // remove headers
        }
      }).then(res => {
        console.log(res);
      }).catch(err => {
        console.log(err.response);
      });

For example, imagine your backend set this cors header.

header("Access-Control-Allow-Methods: GET");

That means a client from a different origin is only allowed to send GET requests, so axios.get would work, axios.post would fail, axios.delete would fail, etc.

Respondent: Eric Guan

Solution #2:

This may occur you are trying call another host for ex- You Vue app is running on localhost:8080 but your backend API is running on http://localhost:8888
In this situation axios request looking for this localhost:8080/project/login instead of this http://localhost:8888/project/login

To solve this issue you need to create proxy in your vue app

Follow this instruction Create js file vue.config.js or webpack.config.js if you haven’t it yet inside root folder

then include below

module.exports = {
 devServer: {
     proxy: 'https://localhost:8888'
 } }

If you need multiple backends use below

module.exports = {
devServer: {
    proxy: {
        '/V1': {
            target: 'http://localhost:8888',
            changeOrigin: true,
            pathRewrite: {
                '^/V1': ''
            }
        },
        '/V2': {
            target: 'https://loclhost:4437',
            changeOrigin: true,
            pathRewrite: {
                '^/V2': ''
            }
        },

    }
}

If you select the second one in front of the end point use the V1 or V2
ex – your end point is /project/login before it use V1/project/login or V2/project/login
as per the host

Respondent: Chameera W. Ashan

Solution #3:

in my case
curl && postman works but not vue axios.post

Access to XMLHttpRequest at ‘http://%%%%:9200/lead/_search‘ from origin ‘http://%%%%.local‘ has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

So, the issue is on vue side not the server!

The server response contains “access-control-allow-origin: *” header

Respondent: Sil2

Solution #4:

I had the same problem even everything was fine on the server side..

The solution to the problem was that API link I hit was missing the slash (/) at the end so that produced CORS error.

Respondent: hljubic

Solution #5:

I’m building an app in Vue.js and added global headers in the main.js file

Example:

axios.defaults.headers.get['header-name'] = 'value'
Respondent: Lindow

Solution #6:

Dev Proxy is your solution

With DevProxy you define a specific path, or a wildcard (non static) that Node (the server runs vue-cli dev server) will route traffic to.

Once defined (a single entry in vue.config.js), you call your api with the same URI as your UI (same host and port) and Vue is redirecting the request to the API server while providing the proper CORS headers.

look more at https://cli.vuejs.org/config/#devserver-proxy

Respondent: Tzury Bar Yochay

Solution #7:

For handling CORS issues you may now have to make changes on the client side, it is not just a server issue.

Chrome has a few plugins: https://chrome.google.com/webstore/search/cors?hl=en

Respondent: user3738936

Solution #8:

You may try :

At the backend,

  1. npm install cors

  2. then, at the backend app.js , add the following,

    const cors = require(‘cors’)

    app.use(cors({
    origin: [‘http://localhost:8082’],
    }))

Hopefully, It may help.

Respondent: Wallace Wong

Solution #9:

in my case adding this in my backend API function it worked

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
        header("Access-Control-Max-Age", "3600");
        header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
        header("Access-Control-Allow-Credentials", "true");

Respondent: kunal rajput

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy