[Vue] 7. 使用axios调用后端接口 (跨域问题解决+415错误解决)

1.安装axios:npm install axios

 

2.如何调用后端接口?

后台接口写法如下:返回结果是个json串,自己随意发挥

@ResponseBody
@RequestMapping(value = "/selShip", method = RequestMethod.POST, produces = "application/json")
    public MyResult selShip(@RequestBody JSONObject jsonParam){

        SHIP ship=JSONUtil.toBean(jsonParam,SHIP.class);
        List<SHIP> shiplist=apiMapper.selectship(ship);
        JSON js=JSONUtil.parse(shiplist);
        System.out.println(js);

        return ResultUtil.success(js);
    }

 

前台Vue  axios写法如下:点击按钮调后端接口

<template>
  <div class="test">
        <el-button  @click="gogo()" >提交</el-button>  
  </div>
</template>



<style scoped></style>

<script>

import axios from "axios";
export default {
  data() {
    return {
      info:"{}"
    };
  },
  methods: {
      gogo(){
          console.log("gogo");
          axios.get('http://localhost:12177/miku1').then(res=>{console.log(res)})
          axios.post('http://localhost:12177/selShip',this.info).then(res=>{console.log(res)})
      }
  },
  mounted() {
      axios.defaults.headers.post['Content-Type'] = 'application/json';
  }
};
</script>

 

调用结果如下:上面红圈是get请求,下面的是post请求的返回结果

3.问题汇总与解决方案

遇到的问题1:前端Vue4 使用 axios post请求后台接口出现 been blocked by CORS policy

解决方案:后端新建配置类允许请求跨域即可

package com.gzgdata.xinshagatepromotion.config;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootConfiguration
public class MyWebConfiger implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry corsRegistry){
        /**
         * 所有请求都允许跨域,使用这种配置就不需要
         * 在interceptor中配置header了
         */
        corsRegistry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("http://localhost:50001")//Vue运行时的地址
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowedHeaders("*")
                .maxAge(3600);
    }

}

 

遇到的问题2:出现415错误

解决方案:axios调用前设置header的Content_Type的值与后端的接口配置一样

axios.defaults.headers.post['Content-Type'] = 'application/json';

 

 

4.axios 封装与拦截器

 

### 如何在 Vue3 和 TypeScript 项目中使用 Axios 调用后端接口 #### 安装依赖 为了在 Vue3 和 TypeScript 项目中使用 Axios,首先需要安装 Axios 库以及其对应的 TypeScript 类型定义文件。可以通过 npm 或 yarn 来完成安装。 ```bash npm install axios @types/axios --save ``` 或者: ```bash yarn add axios @types/axios ``` --- #### 配置 Axios 实例 创建一个专门用于管理 Axios 请求的模块 `http.ts`,以便统一处理请求配置、拦截器等功能。 ```typescript // src/utils/http.ts import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'; const instance: AxiosInstance = axios.create({ baseURL: 'https://your-backend-api.com/api', // 替换为实际的 API 地址 timeout: 10000, }); // 添加请求拦截器 instance.interceptors.request.use( (config: AxiosRequestConfig) => { // 在发送请求之前做些什么,比如添加 token 到 headers 中 config.headers['Authorization'] = localStorage.getItem('token'); return config; }, (error) => { // 对请求错误做些什么 return Promise.reject(error); } ); // 添加响应拦截器 instance.interceptors.response.use( (response) => { // 对响应数据做点什么 return response.data; // 返回 data 字段作为默认解析结果 }, (error) => { // 对响应错误做点什么 if (error.response && error.response.status === 401) { console.error('Unauthorized access!'); } return Promise.reject(error); } ); export default instance; ``` --- #### 创建接口服务层 通过封装具体的业务逻辑来调用后端接口,这样可以提高代码的可维护性和复用性。 ```typescript // src/services/exampleService.ts import http from '@/utils/http'; // 导入 Axios 实例 interface LoginParams { userPhone: string; userPassword: string; } async function login(params: LoginParams): Promise<any> { try { const result = await http.post('/auth/login', params); // 假设登录接口路径为 /auth/login return result; } catch (err) { throw err; } } export { login }; ``` --- #### 在组件中调用接口Vue3 组件中引入并调用封装好的接口方法。 ```typescript <template> <div> <button @click="handleLogin">登录</button> </div> </template> <script lang="ts"> import { defineComponent } from 'vue'; import { login } from '@/services/exampleService'; export default defineComponent({ name: 'ExampleComponent', setup() { async function handleLogin(): Promise<void> { try { const userData = { userPhone: '123123123', userPassword: '123456', }; const response = await login(userData); console.log(response); // 登录成功后的返回数据 } catch (error) { console.error('登录失败:', error.message || error.toString()); } } return { handleLogin, }; }, }); </script> ``` --- #### 注意事项 1. **问题** 如果前后端分离部署,在浏览器环境下可能会遇到 CORS(资源共享)问题。可以在后端设置允许访问的策略[^1]。 2. **Token 管理** 推荐将用户的认证 Token 存储到本地存储(如 `localStorage` 或 `sessionStorage`),并通过 Axios 的请求头自动附加给每次请求[^3]。 3. **错误处理** 在开发过程中应充分考虑各种异常情况下的行为,例如网络超时、未授权访问等,并提供友好的提示信息[^2]。 ---
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值