在Vue項目中如何使用axios發送網絡請求

一、Vue 中的網絡請求

在Vue.js中發送網絡請求本質還是Ajax,我們可以使用插件方便操作。

①vue-resource:Vue.js的插件,已經不維護,不推薦使用。
②axios:不是vue的插件,可以在任何地方使用,推薦使用。
      說明:axios既可以在瀏覽器端又可以在node.js中使用的發送http請求庫,支持Promise語法,不支持jsonp請求(jsonp是解決跨域的)。如果遇到jsonp請求,可以使用插件jsonp實現。

二、axios的引入

① npm i axios
② script src =“cdn 加載”
③script src="./axios.main.js"
引入axios.main.js

在這裏插入圖片描述

三、常用網絡請求方式

1、get

get請求方式將需要入參的數據作爲 params 屬性的值,最後整體作爲參數傳遞。若沒有請求參數,則可省略params屬性。

接口:
在這裏插入圖片描述
在這裏插入圖片描述

data屬性中封裝的對象:
      //查詢所有課程信息的參數對象-簡單搜索
      queryCourseInfo: {
        name: "", //課程名稱
        pageNum: 1, //當前的頁數 。默認頁碼1
        pageSize: 10 //當前每頁顯示多少條數據。默認每頁顯示數量10
      },

上面接口發送請求以及參數拼接可以有以下方式:

A、字符串拼接方式:
Athis.$axios
        .get(
          "/itoo-teach/teach/queryCourseInfoByName?name=" +
            this.queryCourseInfo.name +
            "&pageNum=" +
            this.queryCourseInfo.pageNum +
            "&pageSize=" +
            this.queryCourseInfo.pageSize
        )
        .then(res => {
          if (res.data.code != "0000") {
            return this.$message.error("查詢失敗");
          }
          this.courseList = res.data.data.list;
          this.total = res.data.data.total;
        });

接收到的返回參數res包含的內容如下:
在這裏插入圖片描述

Bconst { data: res } = await this.$axios.get(
        "/itoo-teach/teach/queryCourseInfoByName?name=" +
          this.queryCourseInfo.name +
          "&pageNum=" +
          this.queryCourseInfo.pageNum +
          "&pageSize=" +
          this.queryCourseInfo.pageSize
      );
	      if (res.code != "0000") {
	        return this.$message.error("查詢失敗");
	      }
	      this.courseList = res.data.list;
	      console.log(res);
	      this.total = res.data.total;

變量res解構內容如下(將上方中的res.data進行解構,得到data屬性中的內容):
在這裏插入圖片描述

B、通過params屬性傳遞對象:
Athis.$axios
        .get("/itoo-teach/teach/queryCourseInfoByName", {
          params: this.queryCourseInfo
        })
        .then(res => {
          if (res.data.code != "0000") {
            return this.$message.error("查詢失敗");
          }
          this.courseList = res.data.data.list;
          console.log(res);
          this.total = res.data.data.total;
        });

	【params: this.queryCourseInfo 或者爲:】
	this.$axios
        .get("/itoo-teach/teach/queryCourseInfoByName", {
          params: {
				name:this.queryCourseInfo.name,
				pageNum:this.queryCourseInfo.pageNum,
				pageSize:this.queryCourseInfo.pageSize,
			}
        }) 
        .then(res => {
          if (res.data.code != "0000") {
            return this.$message.error("查詢失敗");
          }
          this.courseList = res.data.data.list;
          console.log(res);
          this.total = res.data.data.total;
        });

接收到的返回參數res包含內容如下:
在這裏插入圖片描述

Bconst { data: res } = await this.$axios.get(
        "/itoo-teach/teach/queryCourseInfoByName",
	        {
	          params: this.queryCourseInfo
	        }
     	 );
	      if (res.code != "0000") {
	        return this.$message.error("查詢失敗");
	      }
	      this.courseList = res.data.list;
	      console.log(res);
	      this.total = res.data.total;

變量res解構內容如下(將上方中的res.data進行解構,得到data屬性中的內容):
在這裏插入圖片描述

C、路徑拼接方式:

接口:
在這裏插入圖片描述
上面接口中的請求參數name需要的類型是path,在url中的呈現的形式是:“接口/參數值”。

    async isExistByName() {
      const { data: res } = await this.$axios.get(
        "/itoo-teach/teach/isExistByName/(最後的“/”爲url後面需要拼接的參數,將url與參數分隔。或者寫成下面的形式)" + this.addCourseList.name(拼接的變量爲 你需要傳遞的參數值)
      );

		const { data: res } = await this.$axios.get(
		        "/itoo-teach/teach/isExistByName"+/+ this.addCourseList.name
	      );
      
      if (res.code != "0000") {
        alert("該課程名稱已存在,請勿重複添加!");
        return;
      }
    },
D、無請求參數:

沒有請求參數的get請求,直接寫需要請求的ur即可:

//查詢機構信息(學院信息)-lz-2020年6月18日18點39分
    async getInstitutionList() {
      const { data: res } = await this.$axios.get(
        "/itoo-teach/teach/queryAllInstitution" 
      ); //無請求參數,直接寫url即可。
      if (res.code != "0000") {
        return this.$message.error("查詢失敗!");
      } else {
        this.institutionNameOptions = res.data;
      }
    },

2、post

A、Content-Type: application/json

json類型,headers裏面設置’Content-Type’: ‘application/json; charset=utf-8’,這種形式的請求,我們只需要在axios的data屬性中傳遞Object對象(參數作爲請求體)即可。
接口:
在這裏插入圖片描述

//data屬性中定義的對象變量:
      //表單信息添加/修改
      addCourseList: {
        // 學院id
        academyId: "",
        //課程代碼
        code: "",
        //課程名稱
        name: "",
        //課程類型
        courseType: "",
        //課程類別
        courseCategory: "",
        //課程性質
        courseNature: "",
        //所屬學院
        institutionName: "",
        //學時
        classHour: "",
        //學分
        classPoint: "",
        //課程分數
        score: ""
      },
① 參數直接傳遞對象:
//添加信息
     const { data: res } = await this.$axios.post(
            "/itoo-teach/teach/create",
            this.addCourseList 【使用data屬性中封裝好的對象】
          );//body請求體  攜帶參數數據
          if (res.code != "0000") {
            return this.$message.error("提交課程信息失敗!");
          }
          this.$refs.addCourseRef.resetFields();
          this.addDialogVisible = !this.addDialogVisible;
          this.getCourseList();
        });
② 通過data屬性傳遞對象:
	// 請求體 data屬性中攜帶參數對象
	 const { data: res } = await this.$axios.post(
            "/itoo-teach/course/create",
            {
              data: { courseModel: this.addCourseList }
            }
          );// courseModel見接口需要的實體參數,保持一致。

headers請求體中包含的內容如下:
在這裏插入圖片描述

B、Content-Type: multipart/form-data

form-data類型,headers裏面設置’Content-Type’: ‘multipart/form-data’,使用data屬性直接傳遞Object對象即可。

① 文件上傳

接口:
在這裏插入圖片描述
實現文件的上傳:使用的是Element ui組件庫中的upload組件

     	<el-upload
          :action="actionUrl"
          ......【其餘配置項略...</el-upload>
data 中配置地址:
actionUrl: process.env.VUE_APP_Back + "itoo-teach/course/importCourse", //上傳文件url 
//方式爲post請求。使用組件上傳,組件中已經爲我們封裝好了請求體部分--默認的參數是file,
//上方接口中的請求參數爲file纔可以,否則前端傳遞的參數是file,
//後端參數如果不是file(比如是mf),後端參數 mf 與 前端參數 file 不對應,則文件將傳不過去。

headers請求體中包含的內容如下:
在這裏插入圖片描述

C、Content-Type: application/x-www-form-urlencoded。

目前這種情況在開發中還沒有遇到過,所以下方圖片並不爲親測,而是來源於網絡。如果後面的開發中遇到這種情況,再進行更新…
在這裏插入圖片描述
在這裏插入圖片描述

3、put

put請求與上面的post請求中json(上面的2-A情況)請求格式類似。
接口:
在這裏插入圖片描述

① 參數直接傳遞對象:
const { data: res } = await this.$axios.put(
            "/itoo-teach/teach/modify",
            this.addCourseList
          );//請求參數封裝在body請求體裏
          if (res.code != "0000") {
            return this.$message.error("修改課程信息失敗!");
          }
          this.$refs.addCourseRef.resetFields();
          this.addDialogVisible = !this.addDialogVisible;
          this.getCourseList();
        });
    },
② 通過data屬性傳遞對象:
const { data: res } = await this.$axios.put(
            "/itoo-teach/teach/modify",
          	 {
              data: { courseModel: this.addCourseList }
             }
          );//請求參數封裝在body請求體裏
          if (res.code != "0000") {
            return this.$message.error("修改課程信息失敗!");
          }
          this.$refs.addCourseRef.resetFields();
          this.addDialogVisible = !this.addDialogVisible;
          this.getCourseList();
        });
    },

4、delete

① 服務端將參數作爲java對象來封裝接收:

delete請求方式:(1)如果服務端將參數作爲java對象來封裝接收,將需要入參的數據作爲 data 屬性的值,最後整體作爲參數傳遞;

② 服務端將參數作爲url參數來接收:

delete請求方式:(2)如果服務端將參數作爲url參數來接受,則請求的url爲:www.demo/url?a=1&b=2形式,使用patams傳遞參數。
【***使用data還是params屬性,看url地址是否有參數拼接。或者看接口,如果參數是body的形式,則使用data屬性傳遞對象】
接口:
在這裏插入圖片描述

//根據所選課程ids,提交要刪除的課程-lz-2020年6月11日16點40分
    async submitDeleteCourse() {
      const { data: res } = await this.$axios.delete(
        "/itoo-teach/teach/deleteByIds",
        {
          data: this.ids
        }
      );//delete需要data屬性攜帶參數,body請求實體
      console.log("批量刪除狀態碼爲:" + res.code);
      if (res.code != "0000") {
        return this.$message.error("刪除課程信息失敗!");
      }
      this.getCourseList();
    },

四、說明:發送請求時使用function/箭頭函數

如果在vue中使用axios發送請求,你在.then/.catch的回調函數中使用了箭頭函數,那麼this指向當前的組件實例。如果回調函數使用的是function函數,那麼this指向undefined…
使用function函數時,vue中data中的數據無法通過this直接引用,需要做如下處理:var _this(vm)=this,先保存一下當前的this,即作用域爲全局對象,否則this在function函數中指向當前對象,這樣的話,在this處(this.$emit…)會發生錯誤 undefined.
在這裏插入圖片描述
或者寫成箭頭函數的形式:
在這裏插入圖片描述
上面兩種方式都可以成功發送請求,不過,使用箭頭函數不支持async函數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章