Search code examples
angulartypescriptcorsspring-restcontroller

Http POST from Angular2 to Rest API [CORS]


I am new to Angular 2 and CORS

I want to post form data from Angular 2 to Rest controller. But i m getting the following error

Response with Status:0 and Url: Null

component.ts
---------------------------------------

onSubmit(form:NgForm) {

console.log(form.value);
var job =  JSON.stringify(form.value);
alert(job); //getting the value



this.jobCleanupService.addJobCleanUp(job).subscribe(
        data =>  alert(data),
        error => alert(error)
    );
   }


jobcleanup.service.ts
----------------------------------

 addJobCleanUp(job:any){
        let headers = new Headers({ 'Content-Type': 'application/json' });
 let options = new RequestOptions({ headers: headers });

        alert('service'+  job); //getting the value

 return this.http.post('http://localhost:8080/addjobcleanup', job,options)
                    .map(res => res.json());
    }

Rest Controller is in different repo

RestController
---------------------------

 @CrossOrigin(origins = "http://localhost:4200/newjobcleanup")
    @RequestMapping(value = "/addjobcleanup" ,method = RequestMethod.POST)
    @ResponseBody
    public String addJobCleanUp(@PathVariable String job) {
        logger.info("Add Job Clean Up");
        return "Success";
    }

Solution

  • You just need to use http://localhost:4200/ as origin, I think this will help.