脚本宝典收集整理的这篇文章主要介绍了Vue3学习(五)之集成HTTP库axios,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
axios
npm install axios@0.21.0 --save
axios
在Vue3新增了SETUP初始化方法,所以我们在这里开始使用并测试,示例代码如下:
<template>
<a-layout>
<a-layout-sider width="200" style="background: #fff">
<a-menu
mode="inline"
v-model:selectedKeys="selectedKeys2"
v-model:oPEnKeys="openKeys"
:style="{ height: '100%', borderRight: 0 }"
>
<a-sub-menu key="sub1">
<template #tITle>
<span>
<user-outlined />
subnav 1
</span>
</template>
<a-menu-item key="1">option1</a-menu-item>
<a-menu-item key="2">option2</a-menu-item>
<a-menu-item key="3">option3</a-menu-item>
<a-menu-item key="4">option4</a-menu-item>
</a-sub-menu>
<a-sub-menu key="sub2">
<template #title>
<span>
<laptop-outlined />
subnav 2
</span>
</template>
<a-menu-item key="5">option5</a-menu-item>
<a-menu-item key="6">option6</a-menu-item>
<a-menu-item key="7">option7</a-menu-item>
<a-menu-item key="8">option8</a-menu-item>
</a-sub-menu>
<a-sub-menu key="sub3">
<template #title>
<span>
<notification-outlined />
subnav 3
</span>
</template>
<a-menu-item key="9">option9</a-menu-item>
<a-menu-item key="10">option10</a-menu-item>
<a-menu-item key="11">option11</a-menu-item>
<a-menu-item key="12">option12</a-menu-item>
</a-sub-menu>
</a-menu>
</a-layout-sider>
<a-layout-content
:style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
>
Content
</a-layout-content>
</a-layout>
</template>
<script lang="ts">
import { definecomponent } From 'vue';
import axios from 'axios';
export default defineComponent({
name: 'Home',
setup(){
console.LOG('set up');
axios.get("http://localhost:8888/eBook/list?name=sPRing").then(response =>{
console.log(response);
})
}
});
</script>
启动服务后,打开主页,并没有任何异常,如下图:
but
,事情并没有我我们想象的那么好,你敢打开F12
看下控制台吗?
有啥不敢的,那我就打开,如下图:
忽略警告部分,红圈部分就是报错了。
报错不要慌,这不是很正常个事吗,有问题解决就好了,很明显就是个跨越问题,简单来说就是,虽然是同一个IP
,但是端口不同,导致没法访问。
可以这样理解,来自一个IP端口的页面(vue
项目),要访问另一个IP端口的资源(springboot
请求接口),会产生跨域访问。
增加Corsconfig
配置类,解决跨域问题,示例代码如下:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.AllowedOriginPatterns("*")
.allowedHeaders(CorsConfiguration.ALL)
.allowedMethods(CorsConfiguration.ALL)
.allowCredentials(true)
.maxAge(3600); // 1小时内不需要再预检(发OPTIONS请求)
}
}
下面就是见证奇迹的时候了,F12
看到真相,忽略警告,可以看到,打印出的response
内容,如下图所示:
这块其实我们也可以使用jquery
来做,都是一样的,具体喜欢哪个,还需要看自己习惯了,到此,集成HTTP
库axios
介绍完,感兴趣的同学请自行尝试。
以上是脚本宝典为你收集整理的Vue3学习(五)之集成HTTP库axios全部内容,希望文章能够帮你解决Vue3学习(五)之集成HTTP库axios所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。