7,vue利用axios调用后台api接口

全代码svn地址 (用户名:liu,密码;123)
通常我们的vue项目是前后分离的,vue前端通过后台api提供的接口(url)操作数据库,这里我们通过axios来实现。
可以使用我的在线API的URL进行测试
和使用swagger构造的API描述文档(81端口的后台已经设置了跨域;82端口的后台没有设置跨域;)
还有在线测试的系统(用户名:liu,密码:12345),有点慢(现在升级为2兆带宽,速度还是可以的了)
在这里插入图片描述

我们后台有这样一个接口:http://localhost:8081/api/projectInfo/GetAll(如果使还没有后台接口,可以先使用http://112.125.90.247:81/api/Data/GetAll这个地址),它的作用是获取projectInfo表的所有数据。在地址栏输入上述地址,看一下结果:
在这里插入图片描述
很明显,只要我们vue前台访问这个地址,就可以拿到这些数据了。下面我们来一步步做:

1,安装axios:

和安其它包一样:npm install axios

2,新建接口文件:

在src文件夹中新建api文件夹,在api文件夹中新建api.js文件(在里面将后台的接口地址稍微修饰,变成前台可以调用的方法):

// 引入axios
import axios from 'axios'
// 请求延时(毫秒数,如果请求话费超过了'timeout'的时间,请求将被中断)
axios.defaults.timeout = 100000

3,写方法:

我们写一个getAllData 方法
这里的params 用来传参,虽然这里还没用到

export const getAllData = params => {
  return axios.get(`http://localhost:8081/api/projectInfo/GetAll`,{ params: params });
};

4,调用方法:

比如我们要在xxx.vue文件里使用这个getAllData 方法:
①先引入方法:

import { getAllData } from '../api/api'

②然后就可以使用getAllData 方法了:

 getAllData().then((res) => {
      console.log(res)
    })

5,运行,看一下是否获取到数据,结果一运行就报错了。

在这里插入图片描述
原来是跨域的错误。

6,跨域修改:

首先我们把在api.js写的方法改一下,改成:

export const getAllData = params => {
  return axios.get(`api/projectInfo/GetAll`,{ params: params });
};

然后为url加一个基础前缀:

axios.defaults.baseURL="/api"

之后,做代理配置:

 proxyTable: {
      // 配置多个代理
      "/api": {
        target: "http://localhost:8081",
        secure:true,
        changeOrigin: true,
        pathRewrite: {
          // 路径重写,
          "^/api": "" // 替换target中的请求地址
        }
      },
    },

(如果你想进行测试而暂时不想自己创建后台,想用上面的在线API URL时,只需要将这里的

target: "http://localhost:8081",

改为:

target: "http://112.125.90.247:81",

target: "http://112.125.90.247:82",

81是后台也进行过跨域配置的接口,82是后台未进行过跨域配置的接口

现在来说一下上述修改起到了什么作用:
我们get.axios里的初始url为api/projectInfo/GetAll,经过axios.defaults.baseURL="/api",要访问的url变为api/api/projectInfo/GetAll
代理配置中的

"/api": {
        target: "http://localhost:8081",

表示,当碰到以/api为前缀的地址时,将/api替换为http://localhost:8081,所以我们现在要访问的地址就是http://localhost:8081/api/projectInfo/GetAll

上述跨域修改是在开发环境中使用,如果是生产环境中则需另做跨域修改,比如使用nginx发布,则需添加配置
(和上面的代理配置是一样的效果)

location ~/api {
			#rewrite ^/api/(.*)$ /$1 break;
			proxy_pass http://127.0.0.1:8081; #接口地址
		}

7,再运行,发现有结果了

在这里插入图片描述
返回的格式不用去管,这是后台配置的,我们只需要看到response里有9011条数据,说明获取数据成功了。

8,新增、编辑、删除的写法

对应在线文档的这三个方法
在这里插入图片描述

/**
 * 数据管理页面新增一条数据
 * @param {*} params
 * qs.stringify()将对象 序列化成URL的形式,以&进行拼接,来传递参数
 * @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"
        }
    }); // 这里是跨域的写法
};

/**
 * 数据管理页面编辑一条数据
 * @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"
        }
    }); // 这里是跨域的写法
};

/**
 * 数据管理页面根据id删除一条数据
 * @param {*} id
 * @returns
 */
export const DeleteDataById = id => {
    return axios.get(`${base}/api/Data/DeleteById/${id}`);
};

其对应的后台代码为:

/// <summary>
		/// 新增数据
		/// </summary>
		///<param name="request">一条数据</param>
		[HttpPost]
		public MessageModel<string> Post([FromBody] Data request)
		{
			var data = new MessageModel<string>();
			request.Id = Guid.NewGuid().ToString();
			request.CreateTime = DateTime.Now;
			//插入数据
			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>
		/// 编辑数据
		/// </summary>
		///<param name="request">一条数据</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>
		/// 根据主键Id删除一条数据
		/// </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;
		}

可能会出现put请求和delete请求不被允许的情况(报405之类的错误),一种解决方法是将put请求改成post请求,将delete请求改成get请求(例如上面的编辑和删除方法)

  • 38
    点赞
  • 202
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
好的,我来为你回答这个问题。 首先,在Vue项目中引入axios需要先安装axios,可以使用以下命令: ``` npm install axios --save ``` 然后在需要使用axiosVue组件中引入axios: ``` import axios from 'axios' ``` 接下来,我们可以使用axios后台发送请求,以下是一个示例: ``` axios.get('/api/users').then(response => { console.log(response.data) }) ``` 上述代码向后台发送了一个GET请求,请求的路径是`/api/users`,并在请求成功后打印了响应数据。 接下来,我们需要后台提供相应的接口来完成增删改查操作。这里以Spring Boot为例,我们可以使用Spring Boot提供的注解来定义RESTful API接口。以下是一个示例: ``` @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @GetMapping public List<User> getUsers() { return userService.getUsers(); } @PostMapping public void addUser(@RequestBody User user) { userService.addUser(user); } @PutMapping("/{id}") public void updateUser(@PathVariable Long id, @RequestBody User user) { userService.updateUser(id, user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userService.deleteUser(id); } } ``` 上述代码中,我们定义了一个`UserController`类,该类提供了四个接口,分别对应了获取用户列表、添加用户、更新用户和删除用户四个操作。其中,`@GetMapping`、`@PostMapping`、`@PutMapping`和`@DeleteMapping`分别对应了HTTP协议中的GET、POST、PUT和DELETE请求。 最后,我们可以在Vue项目中使用axios调用这些接口,以完成增删改查操作。以下是一个示例: ``` // 获取用户列表 axios.get('/api/users').then(response => { console.log(response.data) }) // 添加用户 axios.post('/api/users', { name: '张三', age: 18, gender: '男' }).then(response => { console.log(response.data) }) // 更新用户 axios.put('/api/users/1', { name: '李四', age: 20, gender: '女' }).then(response => { console.log(response.data) }) // 删除用户 axios.delete('/api/users/1').then(response => { console.log(response.data) }) ``` 上述代码分别调用了四个接口,以完成增删改查操作。其中,`axios.post`、`axios.put`和`axios.delete`中的第二个参数分别为要添加、更新和删除的用户数据。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木卯彳亍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值