当前位置: 代码迷 >> java >> Spring Boot AngularJs $http.get 为空
  详细解决方案

Spring Boot AngularJs $http.get 为空

热度:82   发布时间:2023-07-26 14:06:35.0

我正在创建一个资源监视器,用于检索有关位于不同域但相同端口的机器的典型信息。 直接访问url时,数据返回成功。 但是,如果我们使用 angularJs 尝试它,$http.get 请求将返回“被 CORS 策略阻止:请求的资源上不存在‘Access-Control-Allow-Origin’标头”。 我们决定使用 chrome CORS 扩展来允许连接。 唯一的问题是现在 $http.get 请求总是空的,尽管数据存在。 不知道为什么会发生这种情况,因为没有产生错误。

角度控制器

app.controller("ServerResourcesController", [ "$scope", "$http", function($scope, $http) {

     $http.get("http://000.000.0.0:8080/testing")
    .then(function(data){
        console.log(data);
        })
}]);

控制器

@RestController
public class ServerRestController {

    Logger logger = LoggerFactory.getLogger(ServerRestController.class);
    ServerQueryController sqc = new ServerQueryController();

    @RequestMapping("/server-service-info")
    public String ServiceInfo() {//Welcome page, non-rest
        return "Server Resource Monitor Service";
    }

    //rest end point
    @GetMapping("/server-resources-info")
    public ServerInformation ServerInformation() {
        ServerInformation serverInformation = sqc.CurrentServerResourceInformation();
        return serverInformation;
    }
    }

项目等级

@Getter @Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class ServerInformation {

    private String name;
    private String ipAddress;
    private double systemCpuLoad;
    private double freePhysicalMemory;
    private double totalPhysicalMemory;
    private String operatingSystem;
    private double freeDiskSpace;
    private double diskUsage;

    public ServerInformation() {

    }

    @Override
    public String toString() {
        return "Values{ systemCpuLoad: "+systemCpuLoad+
                ", freePhysicalMemory: "+freePhysicalMemory+
                ", totalPhysicalMemory: "+totalPhysicalMemory+
                ", operatingSystem: "+operatingSystem+
                ", freeDiskSpace: "+freeDiskSpace+
                ", diskUsage: "+diskUsage+
                " }";
    }

}

看来你的ServerRestController需要跨域,添加这个

@RestController
@CrossOrigin(origins = "*")
public class ServerRestController {
...
}

另外,如果你想允许一个特定的来源,你可以这样做:

@CrossOrigin(origins = "http://stackoverflow.com", maxAge = 3600)

您可以设置@CrossOrigin与起源,允许和最大年龄无论是在每个方法或在RestController

此外,如果您有多个RestController@CrossOrigin在每个控制器上编写@CrossOrigin并不是最佳做法,您可以像这样创建一个Filter

@Component
public class SimpleCORSFilter implements Filter {

private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

public SimpleCORSFilter() {
    log.info("SimpleCORSFilter init");
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

}

请参阅此处的示例:

  相关解决方案