简体   繁体   English

CORS策略阻止localhost

[英]CORS policy blocks localhost

I made some web project using Spring Boot 2 with rest API. 我使用带有其余API的Spring Boot 2进行了一些Web项目。 I had two projects, the one is rest API, another is web project calling rest API. 我有两个项目,一个是rest API,另一个是调用rest API的Web项目。 I already using @CrossOrigin(origins = "*") . 我已经在使用@CrossOrigin(origins = "*") So, It works well in the controller class. 因此,它在控制器类中效果很好。

However, when I call request to other controller class, chrome print it to me, Access to XMLHttpRequest at 'http://localhost:8080/signout/1234' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. 但是,当我调用其他控制器类的请求时,chrome将其打印给我, Access to XMLHttpRequest at 'http://localhost:8080/signout/1234' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. . How can I solve this problem? 我怎么解决这个问题?

This is my working controller class. 这是我的工作控制器类。 There is no other special in blind space: 盲区没有其他特殊之处:

@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;
    }
...
}

This is working ajax: 这是工作的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);

This is not working controller. 这不是正在工作的控制器。 At first I just used `@CrossOrigin(origins = "*"). 起初我只是使用`@CrossOrigin(origins =“ *”)。

//@CrossOrigin(origins = "http://localhost:8081", allowedHeaders = "*")
@CrossOrigin(origins = "*", allowCredentials = "true", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
@RestController
@RequestMapping("/")
public class UserController {
...
}

This is not working ajax with JWT. 这不适用于JWT。

$.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();

How can I solve this problem? 我怎么解决这个问题?

Option 1 : Add RequestMethod.OPTIONS 选项1添加 RequestMethod.OPTIONS

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

Why OPTIONS? 为什么选择?

This pre-flight request (RequestMethod.OPTIONS) is made by some browsers as a safety measure to ensure that the request being done is trusted by the server. 某些浏览器会发出此飞行前请求(RequestMethod.OPTIONS),这是一项安全措施,以确保服务器信任正在执行的请求。 Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon. 意味着服务器了解请求上发送的方法,源和标头是安全的。


Option 2 : WebConfig for CORS 选项2用于CORS的WebConfig

You can create one WebConfig Class for CORS Origin Configuration so that we don't need to write @CrossOrigin at each and every controller. 您可以为CORS原始配置创建一个WebConfig类,这样我们就不需要在每个控制器上都编写@CrossOrigin

WebConfig.java WebConfig.java

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);
      }

    }

}

Try to add OPTIONS method to the list of allows methods: 尝试将OPTIONS方法添加到OPTIONS方法列表中:

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

OPTIONS method is being used in preflight requests to identify the list of acceptable HTTP methods. 预检请求中使用OPTIONS方法来标识可接受的HTTP方法的列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Cors策略阻止了localhost webapp上的本地开发和localhost访问 - local development on localhost webapp and localhost access blocked by Cors policy React js Cors 策略问题 axios api 在 localhost 如何解决? - React js Cors policy Issue with axios api In localhost How to resove it? 来源 'http://localhost:4200' 已被 CORS 策略阻止 - origin 'http://localhost:4200' has been blocked by CORS policy 'http://localhost:8000' 已被 CORS 策略阻止 - 'http://localhost:8000' has been blocked by CORS policy 来自除本地主机之外的每个来源的 CORS 策略阻止的对外部 API 的 HTTP 请求 - HTTP Request to external API blocked by CORS policy from every origin except localhost localhost:4200 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头 - localhost:4200 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource CORS 策略已阻止从来源“null”访问“https://localhost:44395” - Access to fetch at 'https://localhost:44395' from origin 'null' has been blocked by CORS policy CORS 策略已阻止访问从源“http://localhost:3000”获取 - Access to fetch at from origin 'http://localhost:3000' has been blocked by CORS policy 访问被 CORS 策略阻止的从源 localhost 获取的访问,使用 ajax 的帖子不会。 为什么? - Access to fetch from origin localhost blocked by CORS policy, post using ajax does not. Why? CORS 策略已阻止从源“localhost:3000”访问“...”处的 XMLHttpRequest - Access to XMLHttpRequest at '…' from origin 'localhost:3000' has been blocked by CORS policy
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM