最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

第一次在Vue中完整使用AJAX請求和axios.js的實戰(zhàn)記錄

 更新時間:2022年11月02日 11:29:22   作者:[山青花欲燃]  
AJAX是現(xiàn)代Web開發(fā)的一個關(guān)鍵部分,盡管它一開始看起來令人生畏,但在你的武庫中擁有它是必須的,下面這篇文章主要給大家介紹了關(guān)于第一次在Vue中完整使用AJAX請求和axios.js的相關(guān)資料,需要的朋友可以參考下

零、AJAX

0.0 npm install express

npm i express # 安裝 也可以使用cnpm
npm init --yes # 查看是否安裝到當前環(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) => {
//     // 設置響應頭 設置允許跨域
//     response.setHeader("Access-Control-Allow-Origin", "*");

//     // 設置響應體
//     response.send("HELLO ZHUBA POST");
// });

app.post('/server', (request, response) => {
    // 設置響應頭 設置允許跨域 重點注意此處
    response.setHeader("Access-Control-Allow-Origin", "*");

    // 設置響應體
    response.send("HELLO ZHUBA");
});

app.listen(8000, () => {
    console.log("服務已經(jīng)啟動, 8000端口監(jiā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 請求</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px #90b;
        }
    </style>
</head>
<body>
    <button>點擊發(fā)送請求</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對象
            const xhr = new XMLHttpRequest();
            //2. 設置請求方法和url
            xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&C=300');
            //3. 發(fā)送
            xhr.send();
            //4. 事件綁定 處理服務端返回的結(jié)果
            /*
            on:when:當...時候
            readystate: 是XHR對象中的一個屬性,表示狀態(tài):
                        0(未初始化)
                        1(open方法調(diào)用完畢)
                        2(send方法調(diào)用完畢)
                        3(服務端返回部分結(jié)果)
                        4(服務端返回所有結(jié)果)
            change:改變
            */
            xhr.onreadystatechange = function () {
                //作判斷,是4(服務端返回了所有的結(jié)果)才處理數(shù)據(jù)
                if (xhr.readyState === 4) {
                    //判斷響應狀態(tài)碼:200 404 403 401 500
                    //2XX 都是成功
                    if (xhr.status >= 200 && xhr.status < 300) {
                        //處理服務端響應結(jié)果: 行 頭  空行(咱不管) 體
                        //1. 處理響應行
                        // console.log(xhr.status);//狀態(tài)碼
                        // console.log(xhr.statusText);//狀態(tài)字符串
                        // //2. 所有響應頭
                        // console.log(xhr.getAllResponseHeaders());
                        // //3. 響應體
                        // console.log(xhr.response)
                        //設置result的文本
                        result.innerHTML = xhr.response;
                    } else {

                    }
                }
            }
            // console.log('test'); // test
        }
    </script>
</body>

</html>

Test:

image-20221003104710106

0.3 POST-HTML

需要在express.js中為app添加POST方法(和get一致),并重啟啟動,(正在運行js腳本修改后需要重新啟動)

app.post('/server', (request, response) => {
    // 設置響應頭 設置允許跨域
    response.setHeader("Access-Control-Allow-Origin", "*");

    // 設置響應體
    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 請求</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px #903;
        }
    </style>
</head>

<body>
    <div id="result"></div>

    <script>
        //獲取元素對象
        const result = document.getElementById("result");
        //綁定事件 鼠標移動到上面
        result.addEventListener("mouseover", function () {
            // console.log("test");
            //1. 創(chuàng)建對象,發(fā)送請求
            const xhr = new XMLHttpRequest();
            //2. 初始化 設置請求類型與URL
            xhr.open('POST', 'http://127.0.0.1:8000/server');

            // 如果設置了請求頭需要修改一下發(fā)送內(nèi)容
            //設置請求頭 Content-Type請求體內(nèi)容,application/x-www-form-urlencoded參數(shù) 固定寫法
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            //設置自定義請求頭
            // 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) {
                        //處理服務端返回的結(jié)果
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>

</html>

注意此處:

Test:

一、導入模塊

1.1方法一、下載axios.js,并放入vue工程plugins目錄下

在main.js引入axios

import axios from './plugins/axios

在相應頁面中使用

 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

安裝

// 注意此時只安裝在該工作區(qū)
npm install --save axios

cpnm install --save axios

在相應頁面聲明axios變量

const axios = require('axios');

注意,是在export default外聲明全局變量

使用和之前一樣在相應頁面

1.3方法三直接引入CDN

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

二、實際應用

2.1以為和風天氣API實踐:

[和風天氣](城市信息查詢 - API | 和風天氣開發(fā)平臺 (qweather.com))

2.2數(shù)據(jù)接口如下:

https://geoapi.qweather.com/v2/city/lookup?location=${city}&key=${key}
// city為字符如'北京'
// key為控制臺key

https://devapi.qweather.com/v7/weather/now?location=${data}&key=${key}
// 此處data為前面一個得到的地址的id,如'北京'為:101010100

2.3實現(xiàn):

// 導入axios
const axios = require("axios");
// 異步函數(shù)
async beforeMount() {
    
}
async beforeMount() {
    // 設置好參數(shù)此處寫死的,可以用Vue傳參等
    let key = "fe5812813b8449bb8b4b6ec490ff5cf1";
    let city = "湘潭";
    
    
    // 拼接好請求 把其輸入瀏覽器導航有數(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ù)此處寫死的,可以用Vue傳參等
    let key = "fe5812813b8449bb8b4b6ec490ff5cf1";
    let city = "湘潭";
    
    // 拼接好請求 把其輸入瀏覽器導航有數(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ā)起請求注意此處的await, 不加上,只能得到pending: 初始狀態(tài),不是成功或失敗狀態(tài),如下圖
    let data1 = await axios.get(httpUrl1); //  =Promise{<pending>}
},

promise 要用then接收或者async await

async beforeMount() {
    // 設置好參數(shù)此處寫死的,可以用Vue傳參等
    let key = "fe5812813b8449bb8b4b6ec490ff5cf1";
    let city = "湘潭";
    
    // 拼接好請求 把其輸入瀏覽器導航有數(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ā)起請求注意此處的await, 不加上,只能得到pending: 初始狀態(tài),不是成功或失敗狀態(tài),如下圖
    let data1 = await axios.get(httpUrl1);
    // 輸出想要的數(shù)據(jù),測試一下
    console.log(data);
    console.log(data1.data.location[3]);
},

另一個一樣。

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: "南風",
      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修復

3.1 Can‘t resolve ‘axios‘ in ‘C:\vue\ xxx

axios在當前項目沒安裝,項目未安裝axios依賴,項目根目錄下執(zhí)行下列指令,來安裝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()],
// }

重啟項目后成功。

3.2.2原因分析

原因是由于在webpack5中移除了nodejs核心模塊的polyfill自動引入,所以需要手動引入,如果打包過程中有使用到nodejs核心模塊,webpack會提示進行相應配置。

四、結(jié)合Vue

4.1案例

執(zhí)行 GET 請求

// 為給定 ID 的 user 創(chuàng)建請求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 上面的請求也可以這樣做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

執(zhí)行 POST 請求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

執(zhí)行多個并發(fā)請求

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) {
    // 兩個請求現(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 插件 重試失敗的請求

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 實例
const client = axios.create({ baseURL: 'http://example.com' });
axiosRetry(client, { retries: 3 });

client.get('/test') // 第一次請求失敗,第二次成功
  .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測試

克隆這個倉庫 然后 執(zhí)行:

cnpm test

5.2.vue-axios-plugin

Vuejs 項目的 axios 插件

5.2.1 安裝

可以通過script標簽引入,無需安裝:

<!-- 在 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, {
  // 請求攔截處理
  reqHandleFunc: config => config,
  reqErrorFunc: error => Promise.reject(error),
  // 響應攔截處理
  resHandleFunc: response => response,
  resErrorFunc: error => Promise.reject(error)
})

5.2.3 示例

在 Vue 組件上添加了 $http 屬性, 它默認提供 get 和 post 方法,使用如下:

this.$http.get(url, data, options).then((response) => {
  console.log(response)
})
this.$http.post(url, data, options).then((response) => {
  console.log(response)
})

也可以通過 this.$axios 來使用 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請求和axios.js的文章就介紹到這了,更多相關(guān)Vue使用AJAX請求和axios.js內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue+drf+第三方滑動驗證碼接入的實現(xiàn)

    vue+drf+第三方滑動驗證碼接入的實現(xiàn)

    這篇文章要給大家介紹的是vue和drf以及第三方滑動驗證碼接入的實現(xiàn),下文小編講詳細講解該內(nèi)容,感興趣的小伙伴可以和小編一起來學習奧
    2021-10-10
  • Vue中的計算屬性與監(jiān)聽屬性

    Vue中的計算屬性與監(jiān)聽屬性

    這篇文章介紹了Vue中的計算屬性與監(jiān)聽屬性,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-03-03
  • Vue+thinkphp5.1+axios實現(xiàn)文件上傳

    Vue+thinkphp5.1+axios實現(xiàn)文件上傳

    這篇文章主要為大家詳細介紹了Vue+thinkphp5.1+axios實現(xiàn)文件上傳,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-05-05
  • Vue發(fā)布項目實例講解

    Vue發(fā)布項目實例講解

    在本篇文章里小編給各位分享的是關(guān)于Vue發(fā)布項目的實例內(nèi)容以及知識點講解,需要的朋友們參考下。
    2019-07-07
  • Vue filter格式化時間戳時間成標準日期格式的方法

    Vue filter格式化時間戳時間成標準日期格式的方法

    今天小編就為大家分享一篇Vue filter格式化時間戳時間成標準日期格式的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-09-09
  • vue3如何利用自定義指令實現(xiàn)下拉框分頁懶加載

    vue3如何利用自定義指令實現(xiàn)下拉框分頁懶加載

    下拉框一開始請求第一頁的內(nèi)容,滾動到最后的時候,請求第二頁的內(nèi)容,如此反復,直到所有數(shù)據(jù)加載完成,這篇文章主要介紹了vue3如何利用自定義指令實現(xiàn)下拉框分頁懶加載,需要的朋友可以參考下
    2024-07-07
  • vue設置頁面背景及背景圖片簡單示例

    vue設置頁面背景及背景圖片簡單示例

    這篇文章主要給大家介紹了關(guān)于vue設置頁面背景及背景圖片的相關(guān)資料,在Vue項目開發(fā)中我們經(jīng)常要向頁面中添加背景圖片,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下
    2023-08-08
  • Vue Router中的冗余導航錯誤及解決方案

    Vue Router中的冗余導航錯誤及解決方案

    在現(xiàn)代前端開發(fā)中,單頁應用(SPA)已經(jīng)成為主流,而 Vue.js 作為一款流行的前端框架,其官方路由庫 Vue Router 則是構(gòu)建 SPA 的核心工具之一,在使用 Vue Router 的過程中,開發(fā)者可能會遇到一些常見的錯誤,本文將深入探討這一錯誤的原因、影響以及解決方案
    2025-01-01
  • vue3中el-table實現(xiàn)多表頭并表格合并行或列代碼示例

    vue3中el-table實現(xiàn)多表頭并表格合并行或列代碼示例

    這篇文章主要給大家介紹了關(guān)于vue3中el-table實現(xiàn)多表頭并表格合并行或列的相關(guān)資料,文中通過代碼介紹的非常詳細,對大家學習或者使用vue具有一定的參考借鑒價值,需要的朋友可以參考下
    2024-02-02
  • vue 實現(xiàn)圖片懶加載功能

    vue 實現(xiàn)圖片懶加載功能

    這篇文章主要介紹了vue 實現(xiàn)圖片懶加載功能的方法,幫助大家更好的理解和使用vue,感興趣的朋友可以了解下
    2020-12-12

最新評論

马尔康县| 岳阳县| 兴安盟| 尼勒克县| 黄平县| 治县。| 金川县| 和顺县| 南岸区| 沂源县| 万州区| 苍溪县| 武功县| 新竹市| 高邑县| 乌兰浩特市| 皮山县| 监利县| 博客| 安康市| 临沧市| 钟山县| 新野县| 辽源市| 吉林省| 文化| 剑阁县| 建昌县| 治县。| 军事| 罗源县| 永丰县| 依兰县| 河津市| 牡丹江市| 仁化县| 逊克县| 湘潭市| 聊城市| 新宾| 平和县|