Vue Axios CORS policy: No 'Access-Control-Allow-Origin'

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.


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

For more details visit - Vue official documentation

Tags:

Json

Vue.Js

Axios