1.控制台報錯
Access to XMLHttpRequest at 'http://ip:9999/tradeSale/detail?id=6' from origin 'http://ip:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
2.WebConfig
import com.oigcn.association.common.WebInterceptor; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.*; @Configuration public class WebConfig implements WebMvcConfigurer { @Value("${file.linux.path}") private String path; /** * 攔截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new WebInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/login/**") .excludePathPatterns("/images/**") .excludePathPatterns("/**/page"); } /** * 跨域支持 * @param registry */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowCredentials(true) .allowedHeaders("*") .allowedOrigins("*") .allowedMethods("*") .maxAge(3600); } /** * 文件上傳 * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(path + "**").addResourceLocations("file:" + path); } }
3.WebInterceptor
import com.auth0.jwt.interfaces.DecodedJWT; import com.oigcn.association.utils.TokenUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Slf4j public class WebInterceptor implements HandlerInterceptor { /** * 攔截token * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws AuthException { //加上這段話 String method = request.getMethod(); if(method.equalsIgnoreCase("OPTIONS")){ return true; } String token = request.getHeader("token"); if(StringUtils.isBlank(token)){ log.error("未授權url={}",request.getRequestURI()); throw new AuthException("未授權"); } DecodedJWT jwt = TokenUtil.verify(token); if(jwt != null){ long uid = jwt.getClaim("uid").asLong(); if(uid > 0){ return true; } }else{ throw new AuthException("未授權"); } return false; } }
4.總結
瀏覽器在發送請求時會默認先發送一次類型為’OPTIONS’且不帶任何參數的請求,請求成功后才會發送真正的POST或者GET請求,而在后台攔截器中通常只處理了POST或者get類型的請求,而沒有對OPTIONS類型的請求做處理,因此前端發送的預檢請求無法通過后端的攔截器,導致真正的POST(GET)請求無法發送,要么在前端過濾掉OPTIONS,要么在后台直接返回