Sending a POST request from Angular2 to a REST API with Cross-Origin Resource Sharing (CORS

Just diving into the world of Angular 2 and CORS

Trying to send form data from Angular 2 to a Rest controller, but encountering an 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); //value displayed



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); //value displayed

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

Rest Controller is located in a separate repository

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

Answer №1

If you utilize the URL http://localhost:4200/ as your origin, it should provide the solution you are looking for.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The module has defined the component locally, however, it has not been made available for

I have developed a collaborative module where I declared and exported the necessary component for use in other modules. import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DateslideCompone ...

Check to see whether the coordinates fall inside the specified bounding box

I am faced with the task of creating a function that can determine whether a given coordinate c lies within the boundaries of coordinates a and b. All variables in this scenario are of type: type Coordinate = { lat: number; lon: number; }; Initially ...

ngOnChanges does not track changes made to the form

Currently, I am learning about ngOnChanges directly from the official documentation. However, I have noticed that it is not logging any changes in the HTML form. To address this issue, I made sure to import both FormsModule and ReactiveFormsModule into m ...

Ways to utilize a field from an interface as a type of index

interface Mapping { "alpha": (a: string) => void "beta": (b: number) => void } interface In<T extends keyof Mapping> { readonly type: T, method: Mapping[T] } const inHandlers: In<"alpha"> = { type ...

Retrieve the values of a dynamic JSON object and convert them into a comma-separated string using Typescript

I recently encountered a dynamic JSON object: { "SMSPhone": [ "SMS Phone Number is not valid" ], "VoicePhone": [ "Voice Phone Number is not valid" ] } My goal is to extract the va ...

What is the best way to create a function that can identify and change URLs within a JSON file?

I'm currently working on a function that will replace all URLs in a JSON with buttons that redirect to another function. The modified JSON, complete with the new buttons, will then be displayed on my website. In my component.ts file, the section wher ...

The fusion of Typescript with Node.js

Currently, I am delving into learning typescript and exploring how to integrate it with Node.js. After watching multiple educational videos, I came across two distinct methods for linking typescript with Node.js. The first method involves using decorators, ...

Issue with Materializecss and Angular Cli: The select component is experiencing a dropdown malfunction

I recently integrated materializecss into my angular-cli project, but I am facing an issue with the select components. Upon clicking them for the first time, they do not behave as expected and only show the content after the second click. https://i.sstati ...

Error encountered: ERESOLVE issue occurred while attempting to resolve dependencies during npm install

After attempting to run 'npm install' to download the dependencies from a cloned repository, an error appeared on the terminal. The operating system being used is Windows 10. npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: ...

Error occurs when attempting to test both boolean and number data within an ngIf statement

In the scenario where I am working with a template that includes a boolean called readOnly and an array known as arrayOfStuff: <span *ngIf="!readOnly && arrayOfStuff && arrayOfStuff.length">Hey</span> When running eitherng bui ...

Encountering a MODULE_NOT_FOUND error while trying to execute "npm run build"

I have encountered an issue while trying to deploy my application on my GoDaddy server. Upon running 'npm run build,' I am receiving the following error message: PS C:\Users\trump\Documents\Rider Project\PreChiS-E---Stud ...

Ensure that the status bar remains visible while in full screen mode on Ionic for both android and iOS devices

Greetings! I am currently developing an application with Ionic/Cordova and I have a question regarding enabling the full screen mode while also displaying the status bar. I have already added the following code to my config.xml file: Could someone provide ...

Utilizing Vue 3's Inject Plugin alongside the powerful Composition API and TypeScript

I developed a controller plugin to be used globally in all components, but I am facing challenges making it compatible with Vue 3 + TypeScript + Composition API as I keep getting a TypeScript error. ui/plugins/controllers.ts import { App } from 'vue& ...

Issue with Angular DevExtreme error popup

Currently, I am working on a project using Angular and DevExtreme. Whenever an error occurs, the error message seems to be hidden behind the popup form. Can anyone advise me on how to bring it to the front? Any help would be greatly appreciated. https://i ...

Can one generate an enum based on a specific type?

I have a preference: preference Preference = 'OptionA' | 'OptionB' Is it feasible to generate an enumeration from this preference? For instance: enumeration Enum = { OptionA, OptionB } I am uncertain about the feasibility of this. ...

When attempting to send the token to the server using Angular's WWW-Authenticate: Bearer method, only to encounter a 401

I am a novice in Angular and I have developed a small role-based application using Angular 9 for the frontend and Asp.net core. Everything works fine when I log in or out of the app, and I can access non-Authorize controllers from the frontend without any ...

Exploring the navigation hooks of Angular version 4

Imagine having two components each with their own unique URLs: /dashboard /profile Is there a way to trigger onEnterDashboard when the browser lands on /dashboard, and then have onLeaveDashboard execute when navigating from /dashboard to /profile, follo ...

Contrasting covariant and contravariant positions within Typescript

I'm currently diving into the examples provided in the Typescript advanced types handbook to broaden my understanding. According to the explanation: The next example showcases how having multiple potential values for the same type variable in co-var ...

Implementing a dynamic Bootstrap 4 accordion feature within an Angular project

I have implemented a Bootstrap 4 accordion in my Angular project. Below is the structure of my accordion: <div id="accordion" class="accordion"> <div class="card mb-0"> ...

Error when navigating to a dynamic parameter path using Angular Router

I'm trying to redirect a user to a path with a unique UUID when they go to the root URL (localhost:4200). However, I encountered the following error: ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'document/4fdb ...