Axios 网络请求
文章目录
Axios 网络请求
1.Axios 使用
1.Axios 简介
Axios是封装的Ajax的一个框架
2.Axios 安装
这是官方网站
安装命令
三选一就好,看自己使用的什么包管理器
npm install axios
bower install axios
yarn add axios
https://www.axios-http.cn/docs/intro
3.Axios 引入方式
全局引入
main.js
// 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');
局部引入
import axios from 'axios';
2.整合 vue
请求方式:
1.在组件中使用 axios 发送请求
<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>
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
@CrossOrigin
只需要在需要跨域的控制器上加入 @CrossOrigin
请求结果
已经成功拿到了数据
全局配置 baseUrl
import axios from 'axios'
axios.defaults.baseURL="http://localhost:8088"
app.config.globalProperties.$http = axios
加入这三行代码,必须是 vue 3 ,vue2配置语法不一样
这时候,movie组件中的发送请求代码就可以这样写了
created:function(){
console.log("movie is creating")
this.$http.get("/user").then(function(res){
console.log(res)
})
}
原文地址:https://blog.csdn.net/qq_61715584/article/details/142760016
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!