springboot和vue:十一、Axios网络请求的安装引入与使用、跨域问题解决(CORS)

Axios简介与安装

  • Axios是一个基于promise的网络请求库,作用于node.js和浏览器中
  • Axios在浏览器端使用XMLHttpRequests发送网络请求,并自动完成json数据的转换
  • 安装:npm install axios
  • 官方文档:https://www.axios-http.cn/

Axios基础语法

get请求

当参数比较少时,直接在路径里面用问号拼接传入。

then里面的是个回调函数,原始形态是如下:

复制代码
    axios.get("/user?id=1234")
    .then(function(response){
      //处理成功的情况,走then里面的函数
      console.log(response);
    })
    .catch(function(error){
      //处理错误的情况,走catch里面的函数
      console.log(error);
    })
    .then(function(){
      //总会执行这里面的函数
    });

当参数比较多时,可以使用params传入。

复制代码
    axios.get("/user",{
      params:{
        id:12345
      }
    })
    .then(function(response){
      //处理成功的情况,走then里面的函数
      console.log(response);
    })
    .catch(function(error){
      //处理错误的情况,走catch里面的函数
      console.log(error);
    })
    .then(function(){
      //总会执行这里面的函数
    });

但因为回调函数的作用域改变,如果想要在axios里面使用this指针,会报错undefinded,所以更经常的是如下箭头函数的形式,使得回调函数的作用域和其父级相同。

复制代码
axios.get("/user/findAll")
      .then((response)=> {
        console.log(response);}
        )
      .catch(function (error) {
        console.log(error);
      })
      .then(function () {
        console.log("请求成功发送");
      });

post请求

axios会自动把请求体里的数据,在这里即username和password字段,转成json后传给后端。

复制代码
axios.post("/user",{
      username: 'shanshan',
      password: '12345'
    })
    .then(function(response){
      //处理成功的情况,走then里面的函数
      console.log(response);
    })
    .catch(function(error){
      //处理错误的情况,走catch里面的函数
      console.log(error);
    })
    .then(function(){
      //总会执行这里面的函数
    });

支持async/await用法

复制代码
    async function getUser() {
      try {
        const response = await axios.get('user?id=12345');
        console.log(response);
      } catch (error) {
        console.error(error);
      }
    }

跨域问题

同源策略与CORS

  • 同源策略:为了保证浏览器的安全,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源。
  • 同源:即两个页面具有相同的协议、主机、端口号。
  • 为了解决跨域问题,CORS制定了一个技术标准,使得可以在不破坏既有规则的前提下,通过后端服务器实现CORS接口,从而实现跨域通信。
  • CORS将请求分为两类:简单请求和非简单请求。

GET、POST、application/x-www-form-urlencoded、multipart/form-data、text/plain等常见的请求属于简单请求。
在后端的controller类上面加一个@CrossOrigin注解,即可使得控制器内所有请求都通过跨域问题。

Axios引入与使用

在main.js里写上

复制代码
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:8088'
Vue.prototype.$http = axios

在App.vue里发送axios请求,一般在页面被挂载前就发送

复制代码
export default {
  name: 'App',
  data: function () {
    return {
      movies: [
        { id: 1, title: "金刚狼1", rating: 8.7 },
        { id: 2, title: "金刚狼2", rating: 8.8 },

      ]
    }
  },
  created: function () {
    this.$http.get("/user/findAll")
      .then((response)=> {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      })
      .then(function () {
        console.log("请求成功发送");
      });
  },
  mounted: function () {
    console.log("app被挂载完毕");
  },
  components: {
    Movie
  }
}
相关推荐
运维行者_1 分钟前
网络监控与ITSM集成:从告警到工单,实现运维自动化闭环
开发语言·网络·分布式·后端·架构·flask·php
踩着两条虫4 分钟前
VTJ.PRO AI Agent 技术白皮书
前端·vue.js·低代码
子兮曰4 分钟前
解剖 Claude Code:从入口架构逆向工程看 AI 编程工具的信任边界设计
前端·后端·claude
先吃饱再说16 分钟前
层层传递太“痛”了:useContext 给 React 组件装了个“无线遥控器”
前端·react.js·前端框架
颜进强20 分钟前
前端看后端 15:什么是 DNS?
前端·后端·ai编程
文艺理科生24 分钟前
LangChain.js-v1-记忆管理最佳实践
前端·javascript·后端
麻雀聊技术25 分钟前
一重启 AI 就失忆?用 Spring AI + PostgreSQL 3步搞定“长期记忆”持久化(附完整代码)
java·spring·openai
子兮曰31 分钟前
Elysia vs Hono 完整性能对比:Bun 专属优化还是跨平台通用,2026 实测数据给出的答案
前端·后端·typescript
码农进化录34 分钟前
Java 程序员的 AI 进化论 | LangChain4j 入门,Java 开发者的 AI 应用框架
java·spring boot·openai
小满zs1 小时前
Go语言第七章(Map)
后端·go