选项Http请求失败,但404异常,而Post请求运行正常

时间:2019-07-01 11:57:09

标签: java spring-boot http http-options-method

我在Spring框架中有一个带有可选PathVariable的rest端点。

@PostMapping("/API_PATH/{param1}/{param2}")
public Result getResult(@PathVariable Integer param1,
    @PathVariable(required = false) Integer param2, @RequestBody Data data) {
    // SOME LOGIC HERE
}

我已将param2路径变量标记为不需要。因此,它是一个可选值。当我不向param2发送任何值时,此POST API可以正常工作。但是,当浏览器尝试访问此API时,它将在发送实际的OPTIONS请求之前发送POST类型的请求。现在,如果OPTIONS要求在URL中不包含第二个路径变量(param2),则它会失败并显示404异常。有办法解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

OPTIONS请求是我们在检查安全措施的跨域资源共享(CORS)中所谓的飞行前请求。同样,您可能需要添加CORS配置

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      System.out.println("WebConfig; "+request.getRequestURI());
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Expose-Headers", "Authorization");
      response.addHeader("Access-Control-Expose-Headers", "responseType");
      response.addHeader("Access-Control-Expose-Headers", "observe");
      System.out.println("Request Method: "+request.getMethod());
      if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
          try {
              chain.doFilter(req, res);
          } catch(Exception e) {
              e.printStackTrace();
          }
      } else {
          System.out.println("Pre-flight");
          response.setHeader("Access-Control-Allow-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
          "USERID"+"ROLE"+
                  "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
          response.setStatus(HttpServletResponse.SC_OK);
      }

    }

}

其他一些CORS配置方式 使用CorsRegistry

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**")
        .allowedOrigins("http://domain1.com","http://domain2.com");
}

使用@CrossOrigin

@CrossOrigin(origins = {"http://domain1.com","http://domain2.com"})

使用application.properties

management.endpoints.web.cors.allowed-origins=http://domain1.com,http://domain2.com

答案 1 :(得分:0)

您的代码专门用于POST,因此没有用于OPTIONS的处理程序。 Spring提供了一个CrossOrigin批注,该批注实现了飞行前CORS处理程序,并具有here的读取内容。

尝试一下:

@CrossOrigin
@PostMapping("/API_PATH/{param1}/{param2}")
public Result getResult(@PathVariable Integer param1,
@PathVariable(required = false) Integer param2, @RequestBody Data data) {
    // SOME LOGIC HERE
}