获取“访问控制 - 允许 - 来源”#39;报头'错误

时间:2017-02-22 19:21:23

标签: javascript java angular jersey-2.0

我编写了一个Jersey2 Java API,它是可以访问的。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.ws.rs.*;
import javax.ws.rs.core.*;

@Path("/test")
public class Connect {

    //Vars
    private Connection conn;

    @GET
    @Path("/test")
    @Produces(MediaType.TEXT_PLAIN)
    public String hello(){
        return "helloWorld";
    }

当我使用下面的代码在我的Angular2应用程序中点击这个...

  constructor(HttpWebServiceService1: HttpWebServiceService1){
    HttpWebServiceService1.getHTTP()
      .subscribe(
        resBody => this.title = resBody.title,
        error => console.error('Error: ' + error),
        () => console.log('Completed!')

      );

使用HTTP的类......

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class HttpWebServiceService1 {

      constructor(private http: Http) {}
      getHTTP() {
        return this.http.get('http://localhost:8080/MyApi/test/test').map(
          response =>  response.json());
  }
}

我在浏览器控制台中收到错误...

  

XMLHttpRequest无法加载http://localhost:8080/MyApi/test/test。   No' Access-Control-Allow-Origin'标题出现在请求的上   资源。

帮助!

更新:我导入了cors-filter-2.5-SNAPSHOT.jar。我尝试在我的web.xml中输入以下内容但出现错误...我已经关闭了。我知道有一种方法可以在java中动态地实现它...

<!-- CORS Filter Begin -->
 <filter>
      <filter-name>CORS</filter-name>
      <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
      <init-param>
         <param-name>cors.allowGenericHttpRequests</param-name>
         <param-value>true</param-value>
      </init-param>
      <init-param>
         <param-name>cors.allowOrigin</param-name>
         <param-value>*</param-value>
      </init-param>
      <init-param>
         <param-name>cors.allowSubdomains</param-name>
         <param-value>true</param-value>
      </init-param>
      <init-param>
         <param-name>cors.supportedMethods</param-name>
         <param-value>GET, HEAD, POST, PUT, DELETE, OPTIONS</param-value>
      </init-param>
      <init-param>
         <param-name>cors.supportedHeaders</param-name>
         <param-value>origin, authorization, x-file-size, x-file-name, content-type, accept, x-file-type</param-value>
      </init-param>
      <init-param>
         <param-name>cors.supportsCredentials</param-name>
         <param-value>true</param-value>
      </init-param>
      <init-param>
         <param-name>cors.maxAge</param-name>
         <param-value>3600</param-value>
      </init-param>
   </filter>
   <!-- CORS Filter End -->
<!-- CORS Filter Mappings Begin -->
   <filter-mapping>
      <filter-name>CORS</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
   <!-- CORS Filter Mappings End -->

2 个答案:

答案 0 :(得分:2)

要了解有关错误的更多信息,请查看有关CORS

的详细答案

最简单的方法是在响应中添加标头:

BotController.Player

请参阅此post以获取更多信息。

答案 1 :(得分:0)

使用CORSResponseFilter:

package io.buyr.api.filter;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;

public class CORSResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {

        MultivaluedMap<String, Object> headers = responseContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");
        // mirror back headers - reason: http://stackoverflow.com/a/13147554/873282
        headers.add("Access-Control-Allow-Headers", requestContext.getHeaderString("Access-Control-Request-Headers"));
        headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,HEAD,OPTIONS");
    }

}


public class MyApplication extends ResourceConfig {
    public MyApplication() {
        ...
        register(CORSResponseFilter.class);
        ...
    }

}