Axios 网络请求

文章目录

Axios 网络请求

1.Axios 使用

1.Axios 简介

Axios是封装的Ajax的一个框架

2.Axios 安装

这是官方网站

安装命令

三选一就好,看自己使用的什么包管理器

cpp 复制代码
npm install axios

bower install axios

yarn add axios

https://www.axios-http.cn/docs/intro

3.Axios 引入方式
全局引入

main.js

cpp 复制代码
// src/main.js  
import { createApp } from 'vue';  
import App from './App.vue';  
import axios from 'axios'; // 导入你配置的Axios实例  
  
const app = createApp(App);  
  
// 将axios注册为全局属性  
app.config.globalProperties.$http = axios
axios.defaults.baseURL="http://localhost:8088"

app.mount('#app');
局部引入
cpp 复制代码
import axios from 'axios';

2.整合 vue

请求方式:

1.在组件中使用 axios 发送请求
cpp 复制代码
<template>
    <div>
        <h1>{{ title }}</h1>
    </div>
</template>

<script>
import axios from 'axios';
import { onMounted } from 'vue';
export default {
    name:"Movie",
    props:["title"],
    data:function name(params) {
        return {
           
        }
    },
    created:function(){
        console.log("movie is creating")
        axios.get("http://localhost:8088/user").then(function(res){
            console.log(res)
        })
    }
}


</script>
css 复制代码
  created:function(){
        console.log("movie is creating")
        axios.get("http://localhost:8088/user").then(function(res){
            console.log(res)
        })

这里我选择的是在 movie 组件被创建的时候发送网络请求

发送结果

并且打开我的后端,确认了 localhost :8088/user 这个接口能够获得数据

这里就出现了跨域问题

3.跨域





后端解决办法
全局配置类
加入注解 @CrossOrigin
cpp 复制代码
@CrossOrigin

只需要在需要跨域的控制器上加入 @CrossOrigin

请求结果


已经成功拿到了数据

全局配置 baseUrl
cpp 复制代码
import axios from 'axios'

axios.defaults.baseURL="http://localhost:8088"

app.config.globalProperties.$http = axios

加入这三行代码,必须是 vue 3 ,vue2配置语法不一样

这时候,movie组件中的发送请求代码就可以这样写了

cpp 复制代码
 created:function(){
        console.log("movie is creating")
        this.$http.get("/user").then(function(res){
            console.log(res)
        })
    }
相关推荐
子兮曰2 小时前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭3 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路5 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒6 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
Kagol7 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉7 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau7 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生7 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼7 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范
明君879977 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter