【Vue】集成HTTP库Axios

安装

进入vue项目目录
npm install [email protected] --save

版本

在这里插入图片描述

简单使用

在一个页面中通过axios发送请求拿到后端数据

在这里插入图片描述

Home.vue

import axios from 'axios'; // 1引入库

export default defineComponent({
    
    
  name: 'Home',
  setup(){
    
     // 2初始化方法
      console.log("setup")
      axios.get("http://localhost:8081/hello").then((res)=>{
    
    
          console.log("这是请求返回的数据", res)
      })
  }

});
</script>

问题

解决跨域问题-java配置文件

效果图
在这里插入图片描述

跨域拦截后端不信任前端跨域请求
在这里插入图片描述
在这里插入图片描述

java

package com.bennyrhys.wiki.config;

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;

/**
 * @Author bennyrhys
 * @Date 11/17/21 11:05 PM
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**") // 请求地址
                .allowedOriginPatterns("*") // 允许来源
                .allowedHeaders(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
                .allowCredentials(true) // 凭证比如session cookie
                .maxAge(3600); // 1小时内不需要再预检(前端对后端发OPTION请求)
    }
}

其他报错问题

ctrl+shift+f全局搜索

比如双向绑定的变量暂时还未初始化,先去掉

猜你喜欢

转载自blog.csdn.net/weixin_43469680/article/details/121220332