第一次在Vue中完整使用AJAX請(qǐng)求和axios.js的實(shí)戰(zhàn)記錄
零、AJAX
0.0 npm install express
npm i express # 安裝 也可以使用cnpm npm init --yes # 查看是否安裝到當(dāng)前環(huán)境中
0.1 express.js
// express.js const { response } = require('express'); const express = require('express'); const app = new express(); //app.post('/server', (request, response) => { // // 設(shè)置響應(yīng)頭 設(shè)置允許跨域 // response.setHeader("Access-Control-Allow-Origin", "*"); // // 設(shè)置響應(yīng)體 // response.send("HELLO ZHUBA POST"); // }); app.post('/server', (request, response) => { // 設(shè)置響應(yīng)頭 設(shè)置允許跨域 重點(diǎn)注意此處 response.setHeader("Access-Control-Allow-Origin", "*"); // 設(shè)置響應(yīng)體 response.send("HELLO ZHUBA"); }); app.listen(8000, () => { console.log("服務(wù)已經(jīng)啟動(dòng), 8000端口監(jiān)聽(tīng)中...."); }); // 先運(yùn)行
0.2 GET-HTML
// GET-HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX GET 請(qǐng)求</title> <style> #result { width: 200px; height: 100px; border: solid 1px #90b; } </style> </head> <body> <button>點(diǎn)擊發(fā)送請(qǐng)求</button> <div id="result"></div> <script> //獲取button元素 const btn = document.getElementsByTagName('button')[0]; const result = document.getElementById("result"); //綁定事件 btn.onclick = function () { //1. 創(chuàng)建AJAX對(duì)象 const xhr = new XMLHttpRequest(); //2. 設(shè)置請(qǐng)求方法和url xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&C=300'); //3. 發(fā)送 xhr.send(); //4. 事件綁定 處理服務(wù)端返回的結(jié)果 /* on:when:當(dāng)...時(shí)候 readystate: 是XHR對(duì)象中的一個(gè)屬性,表示狀態(tài): 0(未初始化) 1(open方法調(diào)用完畢) 2(send方法調(diào)用完畢) 3(服務(wù)端返回部分結(jié)果) 4(服務(wù)端返回所有結(jié)果) change:改變 */ xhr.onreadystatechange = function () { //作判斷,是4(服務(wù)端返回了所有的結(jié)果)才處理數(shù)據(jù) if (xhr.readyState === 4) { //判斷響應(yīng)狀態(tài)碼:200 404 403 401 500 //2XX 都是成功 if (xhr.status >= 200 && xhr.status < 300) { //處理服務(wù)端響應(yīng)結(jié)果: 行 頭 空行(咱不管) 體 //1. 處理響應(yīng)行 // console.log(xhr.status);//狀態(tài)碼 // console.log(xhr.statusText);//狀態(tài)字符串 // //2. 所有響應(yīng)頭 // console.log(xhr.getAllResponseHeaders()); // //3. 響應(yīng)體 // console.log(xhr.response) //設(shè)置result的文本 result.innerHTML = xhr.response; } else { } } } // console.log('test'); // test } </script> </body> </html>
Test:
0.3 POST-HTML
需要在express.js中為app添加POST方法(和get一致),并重啟啟動(dòng),(正在運(yùn)行js腳本修改后需要重新啟動(dòng))
app.post('/server', (request, response) => { // 設(shè)置響應(yīng)頭 設(shè)置允許跨域 response.setHeader("Access-Control-Allow-Origin", "*"); // 設(shè)置響應(yīng)體 response.send("HELLO ZHUBA POST"); });
// POST-HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX POST 請(qǐng)求</title> <style> #result { width: 200px; height: 100px; border: solid 1px #903; } </style> </head> <body> <div id="result"></div> <script> //獲取元素對(duì)象 const result = document.getElementById("result"); //綁定事件 鼠標(biāo)移動(dòng)到上面 result.addEventListener("mouseover", function () { // console.log("test"); //1. 創(chuàng)建對(duì)象,發(fā)送請(qǐng)求 const xhr = new XMLHttpRequest(); //2. 初始化 設(shè)置請(qǐng)求類型與URL xhr.open('POST', 'http://127.0.0.1:8000/server'); // 如果設(shè)置了請(qǐng)求頭需要修改一下發(fā)送內(nèi)容 //設(shè)置請(qǐng)求頭 Content-Type請(qǐng)求體內(nèi)容,application/x-www-form-urlencoded參數(shù) 固定寫法 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //設(shè)置自定義請(qǐng)求頭 // xhr.setRequestHeader('name', 'superLmk'); //3.發(fā)送 // xhr.send(); xhr.send('?a=100&b=200&c:300'); // xhr.send('a:100&b:200&c:300'); // xhr.send('123456654123'); //4. 事件綁定 xhr.onreadystatechange = function () { //判斷 if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { //處理服務(wù)端返回的結(jié)果 result.innerHTML = xhr.response; } } } }) </script> </body> </html>
注意此處:
Test:
一、導(dǎo)入模塊
1.1方法一、下載axios.js,并放入vue工程plugins目錄下
在main.js引入axios
import axios from './plugins/axios
在相應(yīng)頁(yè)面中使用
created() { const _this = this axios.get('http://localhost:8181/book/findAll/0/6').then(function(resp){ console.log(resp); _this.tableData = resp.data.content _this.pageSize = resp.data.size _this.total = resp.data.totalElements }) }
1.2方法二使用包管理器安裝axios
安裝
// 注意此時(shí)只安裝在該工作區(qū) npm install --save axios cpnm install --save axios
在相應(yīng)頁(yè)面聲明axios變量
const axios = require('axios');
注意,是在export default外聲明全局變量
使用和之前一樣在相應(yīng)頁(yè)面
1.3方法三直接引入CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
二、實(shí)際應(yīng)用
2.1以為和風(fēng)天氣API實(shí)踐:
[和風(fēng)天氣](城市信息查詢 - API | 和風(fēng)天氣開(kāi)發(fā)平臺(tái) (qweather.com))
2.2數(shù)據(jù)接口如下:
https://geoapi.qweather.com/v2/city/lookup?location=${city}&key=${key} // city為字符如'北京' // key為控制臺(tái)key https://devapi.qweather.com/v7/weather/now?location=${data}&key=${key} // 此處data為前面一個(gè)得到的地址的id,如'北京'為:101010100
2.3實(shí)現(xiàn):
// 導(dǎo)入axios const axios = require("axios");
// 異步函數(shù) async beforeMount() { }
async beforeMount() { // 設(shè)置好參數(shù)此處寫死的,可以用Vue傳參等 let key = "fe5812813b8449bb8b4b6ec490ff5cf1"; let city = "湘潭"; // 拼接好請(qǐng)求 把其輸入瀏覽器導(dǎo)航有數(shù)據(jù)即可,結(jié)果參考下圖 // https://geoapi.qweather.com/v2/city/lookup?location=湘潭&key=fe5812813b8449bb8b4b6ec490ff5cf1 let httpUrl1 = `https://geoapi.qweather.com/v2/city/lookup?location=${city}&key=${key}`; },
async beforeMount() { // 設(shè)置好參數(shù)此處寫死的,可以用Vue傳參等 let key = "fe5812813b8449bb8b4b6ec490ff5cf1"; let city = "湘潭"; // 拼接好請(qǐng)求 把其輸入瀏覽器導(dǎo)航有數(shù)據(jù)即可,結(jié)果參考下圖 // https://geoapi.qweather.com/v2/city/lookup?location=湘潭&key=fe5812813b8449bb8b4b6ec490ff5cf1 let httpUrl1 = `https://geoapi.qweather.com/v2/city/lookup?location=${city}&key=${key}`; // 發(fā)起請(qǐng)求注意此處的await, 不加上,只能得到pending: 初始狀態(tài),不是成功或失敗狀態(tài),如下圖 let data1 = await axios.get(httpUrl1); // =Promise{<pending>} },
promise 要用then接收或者async await
async beforeMount() { // 設(shè)置好參數(shù)此處寫死的,可以用Vue傳參等 let key = "fe5812813b8449bb8b4b6ec490ff5cf1"; let city = "湘潭"; // 拼接好請(qǐng)求 把其輸入瀏覽器導(dǎo)航有數(shù)據(jù)即可,結(jié)果參考下圖 // https://geoapi.qweather.com/v2/city/lookup?location=湘潭&key=fe5812813b8449bb8b4b6ec490ff5cf1 let httpUrl1 = `https://geoapi.qweather.com/v2/city/lookup?location=${city}&key=${key}`; // 發(fā)起請(qǐng)求注意此處的await, 不加上,只能得到pending: 初始狀態(tài),不是成功或失敗狀態(tài),如下圖 let data1 = await axios.get(httpUrl1); // 輸出想要的數(shù)據(jù),測(cè)試一下 console.log(data); console.log(data1.data.location[3]); },
另一個(gè)一樣。
2.4完整Vue:
<template> <div> <h1>obsTime{{ obsTime }}</h1> <h2>text:{{ text }}</h2> <h2>windDir:{{ windDir }}</h2> <h2>windSpeed & windScale::{{ windSpeed }} & {{ windScale }}</h2> </div> </template> <script> const axios = require("axios"); export default { data() { return { cloud: "0", dew: "14", feelsLike: "22", humidity: "69", icon: "150", obsTime: "2022-09-28T22:06+08:00", precip: "0.0", pressure: "1008", temp: "21", text: "晴", vis: "6", wind360: "258", windDir: "南風(fēng)", windScale: "1", windSpeed: "2", }; }, async beforeMount() { let key = "fe5812813b8449bb8b4b6ec490ff5cf1"; let city = "湘潭"; let httpUrl1 = `https://geoapi.qweather.com/v2/city/lookup?location=${city}&key=${key}`; let data1 = await axios.get(httpUrl1); console.log(data1.data.location[3]); let httpUrl = `https://devapi.qweather.com/v7/weather/now?location=${data1.data.location[3].id}&key=${key}`; let data = await axios.get(httpUrl); console.log(data); // data.data.now this.windScale = data.data.now.windScale; this.windSpeed = data.data.now.windSpeed; }, }; </script>
三、BUG修復(fù)
3.1 Can‘t resolve ‘axios‘ in ‘C:\vue\ xxx
axios在當(dāng)前項(xiàng)目沒(méi)安裝,項(xiàng)目未安裝axios依賴,項(xiàng)目根目錄下執(zhí)行下列指令,來(lái)安裝axios依賴:
npm install --save axios
// 然后記得在main.js配置 import axios from 'axios' Vue.prototype.$axios = axios
如果 js-cookie 找不到,還要安裝js-cookie:
npm install --save js-cookie
3.2 webpack < 5 used to include polyfills for node.js core modules by default.
3.2.1解決方案
安裝 node-polyfill-webpack-plugin
npm install node-polyfill-webpack-plugin
vue.config.js中修改配置
// 頭部引入 const NodePolyfillPlugin = require('node-polyfill-webpack-plugin') configureWebpack: (config) => { const plugins = [] plugins.push(new NodePolyfillPlugin()) } // // 或者 // configureWebpack: { // plugins: [new NodePolyfillPlugin()], // }
重啟項(xiàng)目后成功。
3.2.2原因分析
原因是由于在webpack5中移除了nodejs核心模塊的polyfill自動(dòng)引入,所以需要手動(dòng)引入,如果打包過(guò)程中有使用到nodejs核心模塊,webpack會(huì)提示進(jìn)行相應(yīng)配置。
四、結(jié)合Vue
4.1案例
執(zhí)行 GET 請(qǐng)求
// 為給定 ID 的 user 創(chuàng)建請(qǐng)求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 上面的請(qǐng)求也可以這樣做 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
執(zhí)行 POST 請(qǐng)求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
執(zhí)行多個(gè)并發(fā)請(qǐng)求
function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // 兩個(gè)請(qǐng)求現(xiàn)在都執(zhí)行完成 }));
4.2框架整合
vue-axios 基于vuejs 的輕度封裝
4.2.1安裝vue-axios
cnpm install --save axios vue-axios -g //-g:全局安裝
4.2.2加入入口文件
import Vue from 'vue' import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios)
4.2.3使用
Vue.axios.get(api).then((response) => { console.log(response.data) }) this.axios.get(api).then((response) => { console.log(response.data) }) this.$http.get(api).then((response) => { console.log(response.data) })
五、插件
5.1.axios-retry
axios-retry Axios 插件 重試失敗的請(qǐng)求
5.1.1安裝axios-retry
cnpm install axios-retry -g //-g:全局安裝
5.1.2使用
// CommonJS // const axiosRetry = require('axios-retry'); // ES6 import axiosRetry from 'axios-retry'; axiosRetry(axios, { retries: 3 }); axios.get('http://example.com/test') // The first request fails and the second returns 'ok' .then(result => { result.data; // 'ok' }); // Exponential back-off retry delay between requests axiosRetry(axios, { retryDelay: axiosRetry.exponentialDelay}); // Custom retry delay axiosRetry(axios, { retryDelay: (retryCount) => { return retryCount * 1000; }}); // 自定義 axios 實(shí)例 const client = axios.create({ baseURL: 'http://example.com' }); axiosRetry(client, { retries: 3 }); client.get('/test') // 第一次請(qǐng)求失敗,第二次成功 .then(result => { result.data; // 'ok' }); // 允許 request-specific 配置 client .get('/test', { 'axios-retry': { retries: 0 } }) .catch(error => { // The first request fails error !== undefined });
5.1.3測(cè)試
克隆這個(gè)倉(cāng)庫(kù) 然后 執(zhí)行:
cnpm test
5.2.vue-axios-plugin
Vuejs 項(xiàng)目的 axios 插件
5.2.1 安裝
可以通過(guò)script標(biāo)簽引入,無(wú)需安裝:
<!-- 在 vue.js 之后引入 --> <script src="https://unpkg.com/vue"></script> <script src="https://unpkg.com/vue-axios-plugin"></script>
cnpm install --save vue-axios-plugin -g //-g:全局安裝
5.2.2配置入口文件
import Vue from 'Vue' import VueAxiosPlugin from 'vue-axios-plugin' Vue.use(VueAxiosPlugin, { // 請(qǐng)求攔截處理 reqHandleFunc: config => config, reqErrorFunc: error => Promise.reject(error), // 響應(yīng)攔截處理 resHandleFunc: response => response, resErrorFunc: error => Promise.reject(error) })
5.2.3 示例
在 Vue 組件上添加了 $http 屬性, 它默認(rèn)提供 get 和 post 方法,使用如下:
this.$http.get(url, data, options).then((response) => { console.log(response) }) this.$http.post(url, data, options).then((response) => { console.log(response) })
也可以通過(guò) this.$axios 來(lái)使用 axios 所有的 api 方法,如下:
this.$axios.get(url, data, options).then((response) => { console.log(response) }) this.$axios.post(url, data, options).then((response) => { console.log(response) })
總結(jié)
到此這篇關(guān)于第一次在Vue中完整使用AJAX請(qǐng)求和axios.js的文章就介紹到這了,更多相關(guān)Vue使用AJAX請(qǐng)求和axios.js內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue關(guān)閉當(dāng)前彈窗頁(yè)面的兩種方式
這篇文章主要給大家介紹了關(guān)于Vue關(guān)閉當(dāng)前彈窗頁(yè)面的兩種方式,這是最近項(xiàng)目中遇到的一個(gè)需求,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07vue項(xiàng)目如何監(jiān)聽(tīng)localStorage或sessionStorage的變化
這篇文章主要介紹了vue 項(xiàng)目如何監(jiān)聽(tīng)localStorage或sessionStorage的變化,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下2021-01-01vue-router的beforeRouteUpdate不觸發(fā)問(wèn)題
這篇文章主要介紹了vue-router的beforeRouteUpdate不觸發(fā)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04