vue如何利用axios調(diào)用后臺api接口
vue用axios調(diào)用后臺api接口
全代碼svn地址 (用戶名:liu,密碼;123)
通常我們的vue項目是前后分離的,vue前端通過后臺api提供的接口(url)操作數(shù)據(jù)庫,這里我們通過axios來實現(xiàn)。
可以使用我的在線API的URL進行測試
和使用swagger構(gòu)造的API描述文檔(81端口的后臺已經(jīng)設(shè)置了跨域;82端口的后臺沒有設(shè)置跨域;)
還有在線測試的系統(tǒng)(用戶名:liu,密碼:12345),有點慢(現(xiàn)在升級為2兆帶寬,速度還是可以的了)

我們后臺有這樣一個接口:http://localhost:8081/api/projectInfo/GetAll(如果使還沒有后臺接口,可以先使用http://112.125.90.247:81/api/Data/GetAll這個地址),它的作用是獲取projectInfo表的所有數(shù)據(jù)。
在地址欄輸入上述地址,看一下結(jié)果:

很明顯,只要我們vue前臺訪問這個地址,就可以拿到這些數(shù)據(jù)了。
下面我們來一步步做:
1.安裝axios
和安其它包一樣:
npm install axios
2.新建接口文件:
在src文件夾中新建api文件夾,在api文件夾中新建api.js文件(在里面將后臺的接口地址稍微修飾,變成前臺可以調(diào)用的方法):
// 引入axios import axios from 'axios' // 請求延時(毫秒數(shù),如果請求話費超過了'timeout'的時間,請求將被中斷) axios.defaults.timeout = 100000
3.寫方法
我們寫一個getAllData 方法
這里的params 用來傳參,雖然這里還沒用到
export const getAllData = params => {
return axios.get(`http://localhost:8081/api/projectInfo/GetAll`,{ params: params });
};4.調(diào)用方法
比如我們要在xxx.vue文件里使用這個getAllData 方法:
①先引入方法:
import { getAllData } from '../api/api'②然后就可以使用getAllData 方法了:
getAllData().then((res) => {
console.log(res)
})5.運行看一下是否獲取到數(shù)據(jù)
結(jié)果一運行就報錯了。

原來是跨域的錯誤。
6.跨域修改
首先我們把在api.js寫的方法改一下,改成:
export const getAllData = params => {
return axios.get(`api/projectInfo/GetAll`,{ params: params });
};
然后為url加一個基礎(chǔ)前綴:
axios.defaults.baseURL="/api"
之后,做代理配置:
proxyTable: {
// 配置多個代理
"/api": {
target: "http://localhost:8081",
secure:true,
changeOrigin: true,
pathRewrite: {
// 路徑重寫,
"^/api": "" // 替換target中的請求地址
}
},
},
- 如果你想進行測試而暫時不想自己創(chuàng)建后臺,想用上面的在線API URL時,只需要將這里的
target: "http://localhost:8081",
- 改為:
target: "http://112.125.90.247:81",
- 或
target: "http://112.125.90.247:82",
81是后臺也進行過跨域配置的接口,82是后臺未進行過跨域配置的接口
現(xiàn)在來說一下上述修改起到了什么作用:
我們get.axios里的初始url為api/projectInfo/GetAll,經(jīng)過axios.defaults.baseURL="/api",要訪問的url變?yōu)?code>api/api/projectInfo/GetAll。
代理配置中的
"/api": {
target: "http://localhost:8081",
表示,當(dāng)碰到以/api為前綴的地址時,將/api替換為http://localhost:8081,所以我們現(xiàn)在要訪問的地址就是http://localhost:8081/api/projectInfo/GetAll
上述跨域修改是在開發(fā)環(huán)境中使用,如果是生產(chǎn)環(huán)境中則需另做跨域修改,比如使用nginx發(fā)布,則需添加配置
(和上面的代理配置是一樣的效果)
location ~/api {
#rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://127.0.0.1:8081; #接口地址
}
7.再運行,發(fā)現(xiàn)有結(jié)果了

返回的格式不用去管,這是后臺配置的,我們只需要看到response里有9011條數(shù)據(jù),說明獲取數(shù)據(jù)成功了。
8.新增、編輯、刪除的寫法
對應(yīng)在線文檔的這三個方法

/**
* 數(shù)據(jù)管理頁面新增一條數(shù)據(jù)
* @param {*} params
* qs.stringify()將對象 序列化成URL的形式,以&進行拼接,來傳遞參數(shù)
* @returns
*/
export const addData = params => {
return axios.post(`${base}/api/Data/post`, qs.stringify(params), {
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
}
}); // 這里是跨域的寫法
};
/**
* 數(shù)據(jù)管理頁面編輯一條數(shù)據(jù)
* @param {*} params
* @returns
*/
export const editData = params => {
return axios.post(`${base}/api/Data/put`, qs.stringify(params), {
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
}
}); // 這里是跨域的寫法
};
/**
* 數(shù)據(jù)管理頁面根據(jù)id刪除一條數(shù)據(jù)
* @param {*} id
* @returns
*/
export const DeleteDataById = id => {
return axios.get(`${base}/api/Data/DeleteById/${id}`);
};
其對應(yīng)的后臺代碼為:
/// <summary>
/// 新增數(shù)據(jù)
/// </summary>
///<param name="request">一條數(shù)據(jù)</param>
[HttpPost]
public MessageModel<string> Post([FromBody] Data request)
{
var data = new MessageModel<string>();
request.Id = Guid.NewGuid().ToString();
request.CreateTime = DateTime.Now;
//插入數(shù)據(jù)
var id = DbContext.Insertable(request).ExecuteCommand();
//查詢是否添加成功
var success1 = DbContext.Queryable<Data>().Where(it => it.Id == request.Id)
.ToList();
data.success = success1.Count > 0;
if (data.success)
{
data.response = id.ToString();
data.msg = "添加成功";
log4net.ILog log = log4net.LogManager.GetLogger("MyLogger");
log.Info("Data" + "-" + "Add" + "-" + request.Id);
}
return data;
}
/// <summary>
/// 編輯數(shù)據(jù)
/// </summary>
///<param name="request">一條數(shù)據(jù)</param>
[HttpPost]
public MessageModel<string> Put([FromBody] Data request)
{
var data = new MessageModel<string>();
request.UpdateTime = DateTime.Now;
if (request.Id != null)
{
var id = DbContext.Updateable(request).ExecuteCommand();
data.success = (id > 0);
if (data.success)
{
data.msg = "更新成功";
data.response = id.ToString();
log4net.ILog log = log4net.LogManager.GetLogger("MyLogger");
log.Info("Data" + "-" + "Edit" + "-" + request.Id);
}
}
return data;
}
/// <summary>
/// 根據(jù)主鍵Id刪除一條數(shù)據(jù)
/// </summary>
///<param name="Id">編號</param>
[HttpGet]
public MessageModel<string> DeleteById(string Id = "")
{
var data = new MessageModel<string>();
var id = DbContext.Deleteable<Data>().In(Id).ExecuteCommand();
data.success = (id > 0);
if (data.success)
{
data.msg = "刪除成功";
data.response = id.ToString();
log4net.ILog log = log4net.LogManager.GetLogger("MyLogger");
log.Info("Data" + "-" + "Delete" + "-" + Id);
}
return data;
}
可能會出現(xiàn)put請求和delete請求不被允許的情況(報405之類的錯誤)
一種解決方法是將put請求改成post請求
將delete請求改成get請求(例如上面的編輯和刪除方法)
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用vue-element-admin框架從后端動態(tài)獲取菜單功能的實現(xiàn)
​ vue-element-admin是一個純前端的框架,左側(cè)菜單是根據(jù)路由生成的。實際開發(fā)中經(jīng)常需要根據(jù)當(dāng)前登陸人員的信息從后端獲取菜單進行展示,本文將詳細(xì)介紹如何實現(xiàn)該功能2021-04-04
基于vue+elementPlus的動態(tài)導(dǎo)航標(biāo)簽欄tabs具體過程
這篇文章主要給大家介紹了關(guān)于基于vue+elementPlus的動態(tài)導(dǎo)航標(biāo)簽欄tabs的相關(guān)資料,本文主要詳述了在系統(tǒng)上添加導(dǎo)航標(biāo)簽欄功能時,首次嘗試的過程,并且希望能為同行提供一個小demo,需要的朋友可以參考下2024-10-10
Element?Table行的動態(tài)合并及數(shù)據(jù)編輯示例
這篇文章主要為大家介紹了Element?Table行的動態(tài)合并及數(shù)據(jù)編輯示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07

