CORS策略阻止localhost [英] CORS policy blocks localhost

查看:563
本文介绍了CORS策略阻止localhost的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有其余API的Spring Boot 2进行了一些Web项目。我有两个项目,一个是rest API,另一个是调用rest API的Web项目。我已经在使用 @CrossOrigin(origins = *)。因此,它在控制器类中效果很好。

I made some web project using Spring Boot 2 with rest API. I had two projects, the one is rest API, another is web project calling rest API. I already using @CrossOrigin(origins = "*"). So, It works well in the controller class.

但是,当我向其他控制器类调用请求时,chrome将其打印给我,访问来自起源'http:// localhost:8081'的'http:// localhost:8080 / signout / 1234'处的XMLHttpRequest已被CORS策略阻止:对预检请求的响应未通过访问控制检查:它没有HTTP确定状态。。我该如何解决这个问题?

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

这是工作的ajax :

This is working 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 = *)。

This is not working controller. At first I just used `@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 {
...
}

这不适用于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();

如何解决此问题?

推荐答案

尝试将 OPTIONS 方法添加到允许方法列表:

Try to add OPTIONS method to the list of allows methods:

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

选项方法正在预检请求来识别可接受的HTTP方法列表。

OPTIONS method is being used in preflight requests to identify the list of acceptable HTTP methods.

这篇关于CORS策略阻止localhost的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆