使用Axios时,自动发送options 请求的原因

问题

学校课程有一个作业项目,写一个管理项目,后端是SpringBoot2,前端是vue2

在使用axios发送一个携带JSON对象的跨域POST请求时发生了异常,首先用postman测试接口没问题:

postman

但是前端很奇怪,去Chrome的network里面看发现发了两个请求:

一个是正常的请求一个是OPTION类型的预请求

解决方案

其实解决很简单,让Spring正常处理预请求就行,否则,在响应复杂请求时,无法处理预请求而使得请求无法被正常响应

在SpringBoot启动类中添加相应的跨域过滤器

package edu.sdust.javaee.goods; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import tk.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * @author sheny */ @SpringBootApplication @EnableEurekaClient @MapperScan(value = "edu.sdust.javaee.goods.dao") public class GoodsApplication { public static void main(String[] args) { SpringApplication.run(GoodsApplication.class, args); } private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.setAllowCredentials(true); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } }