Javascript CORS策略阻止本地主机

Javascript CORS策略阻止本地主机,javascript,spring,spring-boot,cors,Javascript,Spring,Spring Boot,Cors,我使用带RESTAPI的SpringBoot2制作了一些web项目。我有两个项目,一个是RESTAPI,另一个是调用RESTAPI的web项目。我已经在使用@CrossOrigin(origins=“*”)。因此,它在控制器类中运行良好 然而,当我调用其他控制器类的请求时,chrome会将其打印给我,Access to XMLHttpRequest at'http://localhost:8080/signout/1234“起源”http://localhost:8081'已被CORS策略阻止:

我使用带RESTAPI的SpringBoot2制作了一些web项目。我有两个项目,一个是RESTAPI,另一个是调用RESTAPI的web项目。我已经在使用
@CrossOrigin(origins=“*”)
。因此,它在控制器类中运行良好

然而,当我调用其他控制器类的请求时,chrome会将其打印给我,
Access to XMLHttpRequest at'http://localhost:8080/signout/1234“起源”http://localhost:8081'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:它没有HTTP ok状态。
。我怎样才能解决这个问题

这是我的工作控制器类。在盲区没有其他特殊情况:

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/admin")
public class AdminController {
...
@PutMapping("/users")
public User updateUser(@Valid @RequestBody User updatedUser) throws ResourceNotFoundException {
        User savedUser = userRepository.findByUsername(updatedUser.getUsername());
        savedUser.setPassword(updatedUser.getPassword());
        savedUser = userRepository.save(savedUser);
        return savedUser;
    }
...
}
这就是ajax的工作原理:

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
       if (this.readyState == 4 && this.status == 200){
            ...
        } else if (this.status == 500) {
            alert(this.responseText);
        }
    }

    var json = JSON.stringify(param);
    xmlHttp.open("POST", mainurl+"admin/role", false);
    xmlHttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
    xmlHttp.send(json);
此控制器不工作。起初我只是使用了“@CrossOrigin(origins=“*”)

这不适用于JWT的ajax

$.ajax({
        type: "DELETE", 
        url: "http://localhost:8080/signout/"+username,
        async: true,
//      crossDomain: true,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", 'Bearer '+ "${token}");
        },
        success: function(result, status, xhr){
            //service 표시
        },
        error: function(xhr, status, err) {
            alert(xhr.responseText);
        }
    });

//      var xmlHttp = new XMLHttpRequest();
//      xmlHttp.onreadystatechange = function() {
//          if (this.readyState == 4 && this.status == 200){
//              location.href=window.location.protocol + "//" + window.location.host + "/sso_ui/";
//          } else if (this.status == 500) {
//              alert(this.responseText);
//          }
//      }

//      xmlHttp.open("DELETE", "http://localhost:8080/signout/"+username, false);
//      xmlHttp.setRequestHeader("Content-type", "application/json; charset=utf-8");
//      xmlHttp.setRequestHeader('Authorization', 'Bearer ' + "${token}");
//      xmlHttp.send();
如何解决此问题?

选项1: 添加RequestMethod.OPTIONS

为什么选择

此飞行前请求(RequestMethod.OPTIONS)是由一些浏览器作为安全措施发出的,以确保服务器信任正在执行的请求。这意味着服务器理解在请求上发送的方法、来源和头是可以安全操作的


选项2:CORS的网络配置

您可以为CORS源配置创建一个WebConfig类,这样我们就不需要在每个控制器上编写
@CrossOrigin

WebConfig.java


尝试将
选项
方法添加到允许方法列表中:

@CrossOrigin(origins = "*", allowCredentials = "true", methods = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})

OPTIONS
方法正在中用于标识可接受的HTTP方法列表。

飞行前请求是OPTIONS请求,您尚未在允许的方法中列出该请求。它没有解决我的问题t^t。我尝试应用两个选项。选项1没有解决我的问题。所以,我尝试了选项2。但是,它也没有解决我的问题,出现了一个新问题(关于
@PathVariable
参数)。我该怎么办…?您好@Rect您是否仍面临CORS问题或其他问题。你可以分享更多关于错误的细节,这样我就可以得到更多的ideaHello@Patel Romil,我仍然面临着同样的问题。我想没有更多的细节了。。如果你需要其他信息,请告诉我。我会提供您的请求。您好@Rect您正在谈论
@PathVariable
的一个新问题,因此我了解了一些新问题,
是否存在访问XMLHttpRequest的安装在'http://localhost:8080/signout/1234“起源”http://localhost:8081'已被CORS策略阻止:对飞行前请求的响应未通过访问权限控制检查:它没有HTTP ok状态
@Rect,因此
@PathVariable
是否存在任何问题或错误,或者相同的
已被CORS策略阻止:
 @CrossOrigin(origins = "*", allowCredentials = "true", methods = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
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", "USERID");
      response.addHeader("Access-Control-Expose-Headers", "ROLE");
      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);
      }

    }

}
@CrossOrigin(origins = "*", allowCredentials = "true", methods = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})