0

I have written a Jersey2 Java API and it is reachable.

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

When i hit this in my Angular2 app using below code...

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

      );

With a class for 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());
  }
}

I get an error in the browser console...

XMLHttpRequest cannot load http://localhost:8080/MyApi/test/test. No 'Access-Control-Allow-Origin' header is present on the requested resource.

Help!

Update: I imported cors-filter-2.5-SNAPSHOT.jar. I tried entering the following in my web.xml but got an error...i'm close. I know there is a way to do it in java dynamically...

<!-- 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 -->
Fearghal
  • 10,569
  • 17
  • 55
  • 97

3 Answers3

2

To understand more about the error go through this detailed answer about CORS

The easiest way is to allow add header in your response:

return Response.ok().header("Access-Control-Allow-Origin", "*")

Refer this post to get more idea.

Community
  • 1
  • 1
kpahwa
  • 723
  • 4
  • 7
0

when you are running your app on localhost:some_port and run your server at localhost::other_port than you will get error with Access-Control-Allow-Origin.

you can fix it by convert your localhost (127....) to other url by Hosts file. (C:\Windows\System32\drivers\etc).

<YOUR LOCALHOST IP>  some IP

and than try again

Yoav Schniederman
  • 5,253
  • 3
  • 28
  • 32
  • thx for your response but you will have to elaborate on it...change what url to what url on what file and where? – Fearghal Feb 24 '17 at 19:24
0

USe following 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);
        ...
    }

}
koppor
  • 19,079
  • 15
  • 119
  • 161
  • Thx a mill for the response. Can you hep me understand what im doing above a bit further....I have imported CORS lib...but i don't understand how to use your code...where does my returned value go for e.g. – Fearghal Feb 24 '17 at 19:22