前端设计|Vue 异步请求

Vue 异步请求 Vue 中使用 axios 进行网络请求,使用起来和 jQuery 中的 $.get$.post 功能类似。
安装依赖:cnpm install --save axios
前端设计|Vue 异步请求
文章图片

1. get 请求方式
给定服务器控制器代码,可以接收 name 和 age 参数,设置到 Map 中并返回。
前端设计|Vue 异步请求
文章图片

注意:控制器上有跨域注解。前后端分离都是跨域请求。且端口不能设置 8080 端口,避免端口冲突。

> import axios from "axios" export default { name: 'App', data(){ return{ stu:{ "name":null, "age":null, } } }, mounted(){ //页面加载事件 axios.get("http://localhost:8181/index?name=zhangsan&age=18") .then(res => { console.log(res.data); this.stu = res.data; }) .catch(error => { console.log(error); }) } }

2. post 请求方式
POST 也支持 URL 重写方式传参,即通过 ? 和 & 传递参数,如果使用这种方式传参必须要结合 querystring 使用。
>import axios from "axios" import qstring from "querystring" export default { name: 'App', data(){ return{ name:null, age: null, } }, mounted(){ // 页面加载事件 axios.post("http://localhost:8181/index", qstring.stringify({ name : "张三", age: 23 })) //处理的结果是 name=张三&age=23 .then(res => { console.log(res.data); this.name = res.data.name; this.age = res.data.age; }) .catch(error => { console.log(error); }) } }

后端的业务代码:
@RestController @CrossOrigin//跨域注解 public class TestController {@RequestMapping("/index") public Map, Object> index(@Param("name") String name,@Param("age") Integer age){ Map, Object> result = new HashMap<>(); result.put("name", name); result.put("age", age); return result; } }

3. axios 全局设置
如果使用上面的这种方式,需要在每个页面中都导入 axios,更简便的方式是全局绑定 axios。
修改 main.js
import { createApp } from 'vue' import App from './App.vue'//导入./router/index文件里面配置好的路由 import router from './router/index' import axios from "axios" import qstring from "querystring"//全局Vue对象 const Vue=createApp(App); // 设置axios、qstring全局 Vue.config.globalProperties.$axios=axios; Vue.config.globalProperties.$qstring=qstring; Vue.use(router).mount('#app');

页面中的写法:在任何页面中都可以直接使用 this.$axiosthis.$qstring 进行设置。
> export default { name: 'App', data(){ return{ name:null, age: null, } }, mounted(){ // 页面加载事件 this.$axios.post("/api/index", this.$qstring.stringify({ name: "张三", age: 15 })) .then(res => { console.log(res.data); this.name = res.data.name; this.age = res.data.age; }) .catch(error => { console.log(error); }) } }

4. 请求代理
? ?在 Vue 中发起网络请求时 URL 都使用的是完整的 URL,可以把公共 URL 提出来,提出后发起网络请求时,URL 只写路径部分,省略协议、IP 和端口。
? ?如果没有请求代理,每次在浏览器开发者工具看见真实请求服务器地址,这样话就把服务器暴露给客户端了。使用代理后只能看见代理前请求,保护真实服务器地址。
在项目根路径(不是src)下新建 vue.config.js:
前端设计|Vue 异步请求
文章图片

这个配置文件操作完成后必须重启
const { defineConfig } = require('@vue/cli-service'); module.exports = defineConfig({ transpileDependencies: true, lintOnSave:false, //配置请求代理 devServer: { proxy: { //当请求Vue项目路径都以/api开头时,转发给下面 '/api': { //服务器URL target: "http://localhost:8181/", ws: true, pathRewrite: { //把路径中的api去掉 '^/api': '' }, changeOrigin: true } } } });

【前端设计|Vue 异步请求】发起请求时可以使用 /api/xxx 的形式:
mounted(){ // //页面加载事件 axios.get("/api/index?name=zhangsan&age=18") .then(res => { console.log(res.data); this.name = res.data.name; this.age = res.data.age; }) .catch(error => { console.log(error); }) }

    推荐阅读