1. 程式人生 > >vue axios + Java 跨域 簡潔有效

vue axios + Java 跨域 簡潔有效

要進行跨域訪問,不但 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;
	}
}