-1
// getting cross-origin error in Web API 

    import { Injectable } from '@angular/core';
    import { Http, Headers, Response, RequestOptions } from '@angular/http';
    import { HttpClient, HttpHeaders } from '@angular/common/http'
    import { Observable } from 'rxjs/internal/Observable';
    import { FormGroup, FormBuilder, Validators } from '@angular/forms';
    import { map } from 'rxjs/operators';

    @Injectable()
    export class HomeService {

      constructor(private http: Http) {

      }
      getPrice() {

        const headers = new Headers();
        headers.set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept");
        headers.set("Access-Control-Allow-Origin", "*");

        const options = new RequestOptions({ headers: headers });
        return this.http.get("http://localhost:8084/getPriceDetails", options).pipe(map(data => data))
      };
    }

// Java Class file

package com.xyz.Action;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import org.apache.struts.action.ActionForward;
import org.apache.struts.actions.LookupDispatchAction;
import java.util.ArrayList;

public class dataAction extends LookupDispatchAction {

    private ResourceBundle getResourceBundle() {
        ResourceBundle resourceBundle = null;

        return resourceBundle;
    }

    @Override
    protected Map getKeyMethodMap() {
        Map map = new HashMap();
        map.put("getPriceDetails", "getPriceDetails");
        return map;
    }

    public String getPriceDetails() {

       String str = "In Data Action";
        System.out.println("com.xyz.Action.dataAction.getPriceDetails()"+str);
        return str;
    }
}

I am trying to hit backend(java) from frontend(Angular). But getting this cross-origin issue. so I have added headers as well as but it's not working. I think I have to change in backend code. but not getting where and what.

Java Code (I just created a java application. I am trying to make a communication between frontend and backend.)

Lovely
  • 11
  • 4

1 Answers1

0

If you are using spring-boot just use below configuration. It will work

@Bean
   public WebMvcConfigurer corsConfigurer() {
      return new WebMvcConfigurer() {
         @Override
         public void addCorsMappings( CorsRegistry registry ) {
            registry.addMapping( "/**" )
               .allowedOrigins( "*" )
               .allowedMethods( "*" )
               .allowedHeaders( "*" )
               .allowCredentials( true );
         }
      };
   }

and if spring security enabled use

@Override
protected void configure(HttpSecurity http) throws Exception { 
   http.cors().disable()
......
......
}
Pratap A.K
  • 4,337
  • 11
  • 42
  • 79
  • I didn't set up any spring-boot. just trying to make a connection in between frontend and backend. – Lovely Sep 25 '18 at 11:12