vue-cli+webpack-simple创建项目访问后台(跨域问题解决)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rosemarryTop/article/details/82999750

在网上找了很多都是webpack在config目录下的index.js里面代码,这里总结了一个webpack-simple跨域的问题,在webpack.config.js的devServer中配置:

	devServer:{
		port: 8080,//自己项目的端口
	    host: 'localhost',//自己项目的地址(注意:这里不要加http,具体什么原理容我再研究一下)
	    proxy: {
	      '/api/*': {
	        target: 'http://192.168.x.xxx:xxxx',//跨域要访问的地址及端口
	        changeOrigin: true,
	        secure: false,
	      }
	    }
	}

如果用的事axios访问后台的话,倘若同时请求多个接口,也会出现代理失败的问题,这里分享一个解决方法:

	axios.all([
	      axios.post('/user1'),
	      axios.post('/user2'),
	      axios.post('/user3')
	])
	.then(axios.spread(function (cpResp, cgResp, pdResp) {
	      //回调
	 }));

同时,后台配置(java写法)

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("content-type", "text/html; charset=UTF-8");

注意:

  1. '/api/*'表示 ‘/api’ 请求都会被代理到 target: http://192.168.x.xxx:xxxx 中,如:localhost:8080/api/test会被代理到:http://192.168.x.xxx:xxxx/api/test;
  2. target里面一定要把http带上,我就是没带http然后搞了大半天!
  3. 如果有其他的方法大家可以留言交流。

猜你喜欢

转载自blog.csdn.net/rosemarryTop/article/details/82999750