Skip to content

Instantly share code, notes, and snippets.

@vanholler
Forked from brenopolanski/vue-axios-cors.md
Created October 26, 2020 21:34
Show Gist options
  • Save vanholler/95afb3b4d3c6895a3d01a8489f5241bb to your computer and use it in GitHub Desktop.
Save vanholler/95afb3b4d3c6895a3d01a8489f5241bb to your computer and use it in GitHub Desktop.
Vue.js + Axios + CORS

Proxy requests using Webpack dev server to avoid cors in development mode.

In your webpack.config file add:

"devServer":{
  "proxy": {
    "/api": {
    "target": 'https://my-target.com',
    "pathRewrite": { '^/api': '' },
    "changeOrigin": true,
    "secure": false
    }
  }
}

The above example will proxy the request axios.post(/api/posts/1 ... . . . . to https://my-target.com/posts/1

The above Git example, u need to change like this in your request:

axios.get('/api/a/threads.json', {
	headers: {
           //  if u have some headers like this
	   //  'Authorization': ' Basic //////some values'
	},
	}).then(function (response) {
		console.log('response is : ' + response.data);
	}).catch(function (error) {
		if (error.response) {
		  console.log(error.response.headers);
		} 
		else if (error.request) {
	      console.log(error.request);
		} 
		else {
		  console.log(error.message);
		}
	console.log(error.config);
});

In webpack.config file ........

"devServer":{
  "proxy": {
    "/api": {
    "target": 'https://a.4cdn.org',
    "pathRewrite": { '^/api': '' },
    "changeOrigin": true,
    "secure": false
    }
  }
}

the modified webpack config proxy will change your request like this..

u can see this in chrome dev tool REQUEST HEADERS
https://a.4cdn.org/a/threads.json 

u can use multiple paths in devServer proxy like this In webpack.config file ........

"devServer":{
  "proxy": {
    "/api": {
    "target": 'https://a.4cdn.org',
    "pathRewrite": { '^/api': '' },
    "changeOrigin": true,
    "secure": false
    },
    "/login": {
    "target": 'https://github.com', // for example
    "pathRewrite": { '^/login': '' },
    "changeOrigin": true,
    "secure": false
    },
    "/post": {
    "target": 'https://facebook.com', // for example
    "pathRewrite": { '^/post': '' },
    "changeOrigin": true
    }
  }
}

Use if u need

"changeOrigin": true,
"secure": false

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment