简体   繁体   English

Spring Boot AngularJs $http.get 为空

[英]Spring boot AngularJs $http.get is empty

I am creating a resource monitor that retrieves typical info about a machine on a different domain but same port.我正在创建一个资源监视器,用于检索有关位于不同域但相同端口的机器的典型信息。 When accessing the url directly the data is returned successfully.直接访问url时,数据返回成功。 However if we try it using angularJs the $http.get request would return a "blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource".但是,如果我们使用 angularJs 尝试它,$http.get 请求将返回“被 CORS 策略阻止:请求的资源上不存在‘Access-Control-Allow-Origin’标头”。 We decided to use the chrome CORS extension to allow the connection.我们决定使用 chrome CORS 扩展来允许连接。 Only problem is now the $http.get request is always empty despite the data existing.唯一的问题是现在 $http.get 请求总是空的,尽管数据存在。 Not sure why this is happening as no error is produced.不知道为什么会发生这种情况,因为没有产生错误。

Angular Controller角度控制器

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

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

Controller控制器

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

Object Class项目等级

@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+
                " }";
    }

}

It seems your ServerRestController needs to have cross-origin, add this看来你的ServerRestController需要跨域,添加这个

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

Also, If you want to allow a specific origin you could do it like this:另外,如果你想允许一个特定的来源,你可以这样做:

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

You can set @CrossOrigin with the origins to allow and max age either on each method or on the RestController .您可以设置@CrossOrigin与起源,允许和最大年龄无论是在每个方法或在RestController

Moreover, if you have multiple RestController it's not a best practice to write @CrossOrigin on each and every controller you may just create a Filter like this:此外,如果您有多个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() {
}

}

See the example here: spring cors请参阅此处的示例: spring cors

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM