Vue.js 2.0 版本推薦使用 axios 來完成 ajax 請求。Axios 是一個基於 Promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
axios中文文檔庫:http://www.axios-js.com/zh-cn/docs/
git地址:https://github.com/axios/axios
1.Axios簡單使用
1.axios發送簡單的get請求
后台:
@RequestMapping("/index") @ResponseBody public Map index(HttpServletRequest request, HttpServletResponse response, @RequestParam Map condition) { System.out.println(condition); // 允許ajax跨域請求 response.setHeader("Access-Control-Allow-Origin", "*"); return condition; }
前台:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="js/axios.min.js" type="text/javascript" charset="utf-8"></script> </head> <body> <script> // 為給定 ID 的 user 創建請求 axios.get('http://localhost:8088/weixin/test/index.html?name=zs') .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); }); </script> </body> </html>
結果:
上面的請求還可以:
<script> // 上面的請求也可以這樣做 axios.get('http://localhost:8088/weixin/test/index.html', { params: { name: 'zs2' } }) .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); }); </script>
2.發送POST請求
后台需要過濾器中允許跨域請求:
package cn.qlq.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletResponse; /** * 允許跨域請求 */ @WebFilter(filterName = "corsFilter", urlPatterns = "/*") public class CorsFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println(1); HttpServletResponse response2 = (HttpServletResponse) response; response2.setHeader("Access-Control-Allow-Origin", "*"); // 解決跨域訪問報錯 response2.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response2.setHeader("Access-Control-Max-Age", "3600"); // 設置過期時間 response2.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization"); response2.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP // 1.1. response2.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. // response.setHeader("Expires", // "0"); chain.doFilter(request, response); } @Override public void destroy() { } @Override public void init(FilterConfig arg0) throws ServletException { } }
Controller代碼:
@RequestMapping("/index") @ResponseBody public Map index(HttpServletRequest request, HttpServletResponse response, @RequestBody Map condition) { System.out.println(condition); return condition; }
前台代碼:
<script> axios.post('http://localhost:8088/weixin/test/index.html', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); }); </script>
結果:
post的請求頭Content-Type是application/json,發送JSON數據請求
補充:關於axios中發送同步請求
有時候必須使用同步請求,比如請求回數據之后做其他處理。ajax請求的話使用async:false即可。在axios中的話沒有提供參數,需要借助 async 函數和 await關鍵字。async 是 ES7 才有的。
例如:axios默認異步請求
function test() { console.log(1); axios.post('http://localhost:8088/weixin/test/index.html', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); }); console.log(2); } test();
結果:
發送同步請求:
async function test() { console.log(1); var response = await axios.post('http://localhost:8088/weixin/test/index.html', { firstName: 'Fred', lastName: 'Flintstone' }); console.log(response); console.log(2); } test();
結果:
3.請求配置
{ // `url` 是用於請求的服務器 URL url: '/user', // `method` 是創建請求時使用的方法 method: 'get', // default // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。 // 它可以通過設置一個 `baseURL` 便於為 axios 實例的方法傳遞相對 URL baseURL: 'https://some-domain.com/api/', // `transformRequest` 允許在向服務器發送前,修改請求數據 // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法 // 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data, headers) { // 對 data 進行任意轉換處理 return data; }], // `transformResponse` 在傳遞給 then/catch 前,允許修改響應數據 transformResponse: [function (data) { // 對 data 進行任意轉換處理 return data; }], // `headers` 是即將被發送的自定義請求頭 headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` 是即將與請求一起發送的 URL 參數 // 必須是一個無格式對象(plain object)或 URLSearchParams 對象 params: { ID: 12345 }, // `paramsSerializer` 是一個負責 `params` 序列化的函數 // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` 是作為請求主體被發送的數據 // 只適用於這些請求方法 'PUT', 'POST', 和 'PATCH' // 在沒有設置 `transformRequest` 時,必須是以下類型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 瀏覽器專屬:FormData, File, Blob // - Node 專屬: Stream data: { firstName: 'Fred' }, // `timeout` 指定請求超時的毫秒數(0 表示無超時時間) // 如果請求話費了超過 `timeout` 的時間,請求將被中斷 timeout: 1000, // `withCredentials` 表示跨域請求時是否需要使用憑證 withCredentials: false, // default // `adapter` 允許自定義處理請求,以使測試更輕松 // 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)). adapter: function (config) { /* ... */ }, // `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據 // 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭 auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` 表示服務器響應的數據類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` 允許為上傳處理進度事件 onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` 允許為下載處理進度事件 onDownloadProgress: function (progressEvent) { // 對原生進度事件的處理 }, // `maxContentLength` 定義允許的響應內容的最大尺寸 maxContentLength: 2000, // `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目 // 如果設置為0,將不會 follow 任何重定向 maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項: // `keepAlive` 默認沒有啟用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' 定義代理服務器的主機名稱和端口 // `auth` 表示 HTTP 基礎驗證應當用於連接代理,並提供憑據 // 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設置的自定義 `Proxy-Authorization` 頭。 proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` 指定用於取消請求的 cancel token // (查看后面的 Cancellation 這節了解更多) cancelToken: new CancelToken(function (cancel) { }) }
4.響應結構
{ // `data` 由服務器提供的響應 data: {}, // `status` 來自服務器響應的 HTTP 狀態碼 status: 200, // `statusText` 來自服務器響應的 HTTP 狀態信息 statusText: 'OK', // `headers` 服務器響應的頭 headers: {}, // `config` 是為請求提供的配置信息 config: {}, // 'request' // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance the browser request: {} }
補充:關於axios攔截器的使用
有時候希望發送請求處理之前和之后做一些處理。比如說每個請求攜帶token參數,接收消息之后根據回傳的結果驗證是否正確,不正確統一處理。
前端代碼:
// 添加請求攔截器 axios.interceptors.request.use(function(config) { // 模擬處理前增加token console.log("處理前 "); config.data.token = "123456"; return config; }, function(error) { // 對請求錯誤做些什么 return Promise.reject(error); }); // 添加響應攔截器 axios.interceptors.response.use(function(response) { // 對響應數據做點什么 console.log("處理后"); if(response.data.success) { // 如果是成功返回信息之后提取出來返回以供后面的調用鏈使用 return response.data.data; } else { // 如果返回false記錄一下返回Promise 對象。不會執行當前promise. console.log(response.data.msg); return new Promise(function(resolve, reject) { // resolve('success1'); // reject('error'); }); } }, function(error) { // 對響應錯誤做點什么 return Promise.reject(error); }); function test() { axios.post('http://localhost:8088/test/test.html', { firstName: 'Fred', lastName: 'Flintstone' }).then(function(resData) { // 這里處理返回的data console.log(resData); }); } test();
后端返回的JSON工具類:
package cn.qs.utils; import java.io.Serializable; public class JSONResultUtil<T> implements Serializable { private static final long serialVersionUID = 3637122497350396679L; private boolean success; private T data; private String msg; public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public T getData() { return data; } public void setData(T data) { this.data = data; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public JSONResultUtil(boolean success) { this.success = success; } public JSONResultUtil(boolean success, String msg) { super(); this.success = success; this.msg = msg; } public JSONResultUtil(boolean success, T data, String msg) { super(); this.success = success; this.data = data; this.msg = msg; } /** * 返回正確結果不帶數據 * * @return */ public static JSONResultUtil ok() { return new JSONResultUtil(true); } /** * 返回錯誤的結果帶錯誤信息 * * @param msg * @return */ public static JSONResultUtil error(String msg) { return new JSONResultUtil(false, msg); } }
Controller返回正確:
@PostMapping("/test") public JSONResultUtil<String> Test(@RequestBody String condition) { System.out.println(condition); return new JSONResultUtil<String>(true, condition, "ok"); }
結果:
Controller返回false:
@PostMapping("/test") public JSONResultUtil<String> Test(@RequestBody String condition) { System.out.println(condition); return new JSONResultUtil<String>(false, null, "error"); }
結果:
2.vue中使用axios
1. 簡單使用
后端代碼:
@RequestMapping("/index") @ResponseBody public Map index(HttpServletRequest request, HttpServletResponse response, @RequestBody Map condition) { condition.put("name", "zs"); condition.put("age", 25); return condition; }
前台:(請求后台的JSON數據,並且將得到的數據直接賦值給自己的data屬性,自己的data原來為null)
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="js/vue.min.js" type="text/javascript" charset="utf-8"></script> <script src="js/axios.min.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div id="app"> <h1>{{ data.name }} - {{ data.age }}</h1> </div> <script type="text/javascript"> new Vue({ el: '#app', data: { data: null }, mounted() { axios .post('http://localhost:8088/weixin/test/index.html', { 'test': 123 }) .then(response => (this.data = response.data)) .catch(function(error) { // 請求失敗處理 console.log(error); }); } }) </script> </body> </html>
結果:
2. 請求圖片流
1.方法一:
第一種方法就是向后台請求一個圖片URL,然后改變image的src屬性實現,其靜態實例如下:
<div id="vue_det"> <img :src="src" /> </div> <script type="text/javascript"> var vm = new Vue({ el: '#vue_det', data: { src: "http://localhost:8088/static/images/1.png", } }) </script>
2.方法2:
使用JS請求數據流。
<div id="vue_det"> <img :src="imgUrl" class="logoImg"> </div> <script type="text/javascript"> var vm = new Vue({ el: '#vue_det', data: { imgUrl: '123' }, mounted: function() { var url = 'http://localhost:8088/static/images/1.png'; axios.get(url, { responseType: 'arraybuffer' }).then(function(data) { vm.imgUrl = 'data:image/png;base64,' + btoa(new Uint8Array(data.data).reduce((data, byte) => data + String.fromCharCode(byte), '')) console.log(this.imgUrl) }).catch(function(err) { console.error(err) }); } }) </script>
注意:
(1)vue組件或者實例中,不管是生命周期鈎子函數created還是自定義函數plus,他們中的this都是指當前vue實例。
(2)回調函數中,如果是普通函數,this指向window對象,如果是 ES6的 =>箭頭函數,this指向當前實例。所以建議一般情況下用箭頭函數指向當前實例。
<script type="text/javascript"> var vm = new Vue({ el: '#vue_det', data: { imgUrl: '123' }, mounted: function() { console.log(this); var url = 'http://localhost:8088/static/images/1.png'; axios.get(url, { responseType: 'arraybuffer' }).then(function(data) { console.log(this); vm.imgUrl = 'data:image/png;base64,' + btoa(new Uint8Array(data.data).reduce((data, byte) => data + String.fromCharCode(byte), '')) }).catch(function(err) { console.error(err) }); } }) </script>
結果:
<script type="text/javascript"> var vm = new Vue({ el: '#vue_det', data: { imgUrl: '123' }, mounted: function() { console.log(this); var url = 'http://localhost:8088/static/images/1.png'; axios.get(url, { responseType: 'arraybuffer' }).then(data => { console.log(this); this.imgUrl = 'data:image/png;base64,' + btoa(new Uint8Array(data.data).reduce((data, byte) => data + String.fromCharCode(byte), '')) }).catch(function(err) { console.error(err) }); } }) </script>
結果:
補充:如果想在函數普通回調函數中用當前vue實例對象,可以在外面提前將this付給一個變量,例如:
async onChangeKindergarten(value) { // 將_this指向當前vm對象 const _this = this; var confirmContent = '您確定要選擇 ' + value + ' 嗎?您只有一次修改的機會!'; this.$vux.confirm.show({ title: '', content: confirmContent, onConfirm() { axios.post('/user/updateLoginUser.html', { remark1: value }); _this.remark1 = value; _this.$vux.toast.text('修改成功'); }, onCancel() { _this.remark1 = ''; } }) }