vue axios + Java 跨域 简洁有效

版权声明:借鉴时注明出处就行 https://blog.csdn.net/weixin_42144379/article/details/86000315

要进行跨域访问,不但 vue 的 axios 要设置 ,服务端也要设置

我提供了一种配置方法,相对于 修改vue的config 文件还是比较简洁的

 1.在 vue main.js 的 里面

import axios from 'axios'//引入axios,来发送请求

Vue.prototype.axios = axios //设置axios全局引用

axios.defaults.timeout = 5000;// 在超时前,所有请求都会等待 5 秒
// 配置请求头
axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = 'http://localhost:8080/jacktu';// 配置接口地址
axios.defaults.withCredentials = false;

2.在 Java 后端

一般情况:

// 指定允许其他域名访问
response.setHeader("Access-Control-Allow-Origin", "*");//此句是关键,其他不重要

// 响应类型
response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");

// 响应头设置
response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token");

如果你用的是 Spring 的话,使用 @CrossOrigin(origins = "*") 就可以

//@CrossOrigin("http://127.0.0.1:9090")
// * 是代表允许任何跨域
@CrossOrigin(origins = "*", maxAge = 3600)//就是这个注解
@Controller
@RequestMapping(value = "/zhaopin")
public class ZhaoPinController {
	@Autowired
	private ZhaoPinService service;

3.调用 写在 App.vue <script></script>里面的:

然后, 启动vue 项目 打开控制台

export default {
  components:{
	},
	data(){
		return{}
	},
	methods:{
	},
//vue启动,会自动执行 mounted里面的代码
	mounted() {
            //这里面才是关键,其他都不重要
			this.axios({
				method: 'get',
				url: '/test/test.do',//会自动添加main.js里面的配置
				params: this.urlParams
			}).then((res) => {
				console.log(res)
				console.log(res.data)
				alert(res.data.msg)
			}).catch((err) => {
				console.log(err)
			})
	}
}

4.出现错误:

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

如果出现,类似这样的错误,则是由于 后端配置错误,检查后端.

 5.最后,附上个人相关完整代码:

vue 里面的 main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App'
import axios from 'axios'//引入axios,来发送请求

Vue.config.productionTip = false
Vue.use(ElementUI)

Vue.prototype.axios = axios

axios.defaults.timeout = 5000;// 在超时前,所有请求都会等待 5 秒
axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded;charset=UTF-8';// 配置请求头
axios.defaults.baseURL = 'http://localhost:8080/jacktu';// 配置接口地址
axios.defaults.withCredentials = false;

new Vue({
	el: '#app',
	components: {App},
	template: '<App/>'
	// render: h => h(App)
})

vue 里面 App.vue

<template>
  <div>
    <el-menu></el-menu>
		<el-table></el-table>
		<br/>
		<el-page></el-page>
  </div>
</template>

<script>
import nav from "./components/NavMenu.vue"
import eletable from "./components/Table.vue"
import pageination from "./components/Pagination.vue"
export default {
  components:{
		ElMenu:nav,
		ElTable:eletable,
		ElPage:pageination
	},
	data(){
		return{}
	},
	methods:{
		
	},
	mounted() {
			this.axios({
				method: 'get',
				url: '/test/test.do',
				params: this.urlParams
			}).then((res) => {
				console.log(res)
				console.log(res.data)
				alert(res.data.msg)
			}).catch((err) => {
				console.log(err)
			})
	}
}
</script>



Java 的 Controller 我使用的 是 Spring MVC 有Spring 就行:

package top.jacktu.page.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/test")
@CrossOrigin(origins = "*", maxAge = 3600)
public class TestController {
	//http://localhost:8080/jacktu/test/test.do
	@RequestMapping("/test")
	@ResponseBody
	public Map<String, Object>  hello(HttpServletRequest request,HttpServletResponse response) {
		HashMap<String, Object> map = new HashMap<>();
		map.put("page", "jakctu's personal page");
		map.put("msg", "你好");
		return map;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42144379/article/details/86000315
今日推荐