Skip to content

Instantly share code, notes, and snippets.

@brenopolanski
Last active August 14, 2023 10:10
Show Gist options
  • Save brenopolanski/7f084f2ab8f817f6160deae1be629520 to your computer and use it in GitHub Desktop.
Save brenopolanski/7f084f2ab8f817f6160deae1be629520 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:

@samuelkilada
Copy link

Wow, this actually works! Every other example I've followed has failed. I think the key that the other examples were missing is:

"pathRewrite": { '^/api': '' },

@dulerong
Copy link

dulerong commented Jun 4, 2022

This solution worked wonderfully, straightforward, concise and self explanatory, great!!!

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