[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 封装与拦截器

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值