[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 shiplist=apiMapper.selectship(ship);
        JSON js=JSONUtil.parse(shiplist);
        System.out.println(js);

        return ResultUtil.success(js);
    }

 

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







 

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

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

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';

 

你可能感兴趣的:(前端--Vue&Angular,vue)