Troubleshooting Angular: Dealing with Cross-Origin Resource Sharing (CORS) issue

I am currently facing an issue with posting data to elasticsearch from my service. The CORS policy is blocking the action and even after attempting to use a proxy script, the error persists. Can anyone offer assistance in resolving this?

Here is the proxy file content:

{
  "/rest/elastic/*": {
    "target": "http://xx.xx.xx.xx/",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

This is my service:

import { Injectable } from '@angular/core';
import {HandleError, HttpErrorHandler} from '../http-error-handler.service';
import {HttpClient, HttpHeaders} from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
};

const userID = '5eada3f00952b44e417fcf82';

@Injectable({
  providedIn: 'root'
})
export class PostServiceService {

  postElasticUrl = 'http://xx.xx.xx.xx:9200/post/_doc';


  private handleError: HandleError;

  constructor(
    private http: HttpClient,
    httpErrorHandler: HttpErrorHandler) {
    this.handleError = httpErrorHandler.createHandleError('TimelineService');
  }

  /** POST Moods to the server */
  postMoods(emoji, text) {

    this.http.post<any>(this.postElasticUrl, '{"emoji":"' + emoji + '","text":"' + text + '","userID":"' + userID
      + '","timestamp":"' + Date.now() + '" }', httpOptions).subscribe();
  }
}

And I am executing the project using:

ng serve --proxy-config proxy.conf.json

The request body is structured as follows:

{emoji: "confused", 
text: "dsv", 
userID: "5eada3f00952b44e417fcf82", 
timeStamp: 1590233638000}

Answer №1

To accept requests from the UI, ensure that CORS is enabled on the Elastic Search server.

For assistance with enabling CORS, you can refer to this link:

Remember not to set the origin as *, but to use the exact origin of your UI.

When sending data in a POST request, ensure it is in JSON format. Here's an example:

let req = {
   emoji,
   text,
   userId,
   timeStamp: Date.now(),
}
this.http.post<any>(this.postElasticUrl, req, httpOptions).subscribe();

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

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

The designated route, "**", is for displaying a page that cannot be found

Utilizing routing in Angular 2 with TypeScript has been a beneficial choice for my project. In the main index.html, I included <base href=""> instead of <base href="/"> to accommodate a specialized route requirement. This setup has been effecti ...

Zod offers the flexibility to customize validation for optional keys

Currently, I am exploring the utility of using zod within my application. I am facing a minor issue when attempting to parse an object that may contain optional keys. While using .passthrough allows the keys to remain in the object, I am interested in cu ...

Trigger event when ngModel changes

Currently, I am trying to perform a test on a select element... <select [ngModel]="selectedRouters" name="routerName" class="form-control" id="routersSelect" size="12" (ngModelChange)="selectRouters($event)" multiple> <option [value]="route ...

Is it necessary to include explicit overlapping imports in Angular if they are already imported in the parent component?

Do you think the title needs clarification? Feel free to offer suggestions. I've noticed that my design components are ending up with a lot of imports. Some of these imports are duplicated in the component that is importing them. I'm managing to ...

Unable to access the API within Angular using a web browser

My Angular application is hosted within an ASP.NET Core application on IIS. The API controller of the ASP.NET Core application can be accessed using the HTTP client in Angular as well as in a C# console application. However, I am facing an issue where I c ...

Exploring the versatility of Highcharts with callback functions and comprehensive

Currently, I am utilizing Highcharts with angular 9. Here is the link to the code : https://stackblitz.com/edit/angular-ivy-wdejxk For running on the application side or test side, follow these instructions: Test Side: In the angular.json file at line ...

Occasionally, angulafire2's getDownloadURL() function may fail to work with Angular. Could this be due to asynchronous processes?

Receive a 404 error when trying to access . Firebase is reporting a download link error with the following message: "Firebase Storage: Object 'hw04.docx' does not exist." Below is the code snippet related to this issue. upload(event) { cons ...

Angular is unable to iterate through a collection of ElementRef instances

My list of ElementRef contains all my inputs, but adding listeners to them seems to indicate that textInputs is empty even though it's not. @ViewChildren('text_input') textInputs!: QueryList<ElementRef>; ngAfterViewInit(): void { ...

Angular 4's ngOnChanges method does not display the updates made

I've been attempting to utilize ngOnChanges in Angular 4, but I haven't been able to get it to work. login.component.ts import { AuthService } from './../../services/auth.service'; import { ActivatedRoute, Router } from '@ang ...

Defining Objects in TypeScript

Within my TypeScript application, I currently have the following code: interface Data { url: string, // more stuff } (...) export class something() { public data: Data; } method(){ this.data.url = "things"; } However, every time I atte ...

The validation using regex is unsuccessful when the 6th character is entered

My attempt at validating URLs is encountering a problem. It consistently fails after the input reaches the 6th letter. Even when I type in "www.google.com," which is listed as a valid URL, it still fails to pass the validation. For example: w ww www ww ...

Arrange two input fields side by side if the quantity of input fields is unspecified

I am currently in the process of developing a project using Angular. I have implemented an *ngFor loop to dynamically add input fields based on the data retrieved from the backend. Is there a way I can ensure that two input fields are displayed on the same ...

Working with nested arrays in TypeScript and how to push values onto them

I am facing some challenges with nested array behavior in TypeScript. I am looking for a way to define a single type that can handle arrays of unknown depth. Let me illustrate my issue: type PossiblyNested = Array<number> | Array<Array<number& ...

Issue with displaying Typescript sourcemaps on Android device in Ionic 2

Encountering a strange behavior with Ionic2. After deploying my app to a simulator, I am able to view the .ts file sourceMap in the Chrome inspect debugger. In both scenarios, I use: ionic run android https://i.sstatic.net/JarmI.png However, when depl ...

Angular 5 throwing an error - trying to access a property that is undefined

In my form, each div contains a label, checkbox, and input field. When the menu is opened, all checkboxes are initially unchecked, disabling all input fields. You can then enable an input field by checking its corresponding checkbox. I attempted to implem ...

Global Enum in Typescript that is Optimized for Inlining during Compilation

I'm facing a challenge with an enum that is widely used in my project. Having to import it into every file is becoming cumbersome. Is there a way to define the enum in the .d.ts file so that it automatically gets included when compiled to Javascript? ...

Transferring information between two components remains intact even after refreshing the page

The component product-list is responsible for showcasing all the products available: <div *ngFor="let product of products"> <a routerLink="/products/{{ product.url }}" [state]="product">{{ product.name }}</a> <p>{{ product.url ...

Issue with JSON encoding in Embed message/interaction reply in Discord.js v14

I am currently utilizing Discord.js version 14.8, which was developed in typescript. Here is a snippet from my package.json file: "dependencies": { "@discordjs/rest": "^1.1.0", "@supabase/supabase-js": &quo ...

Trouble arises when default route in Angular uses '' and '**' for 404 errors as intended

Within my app-routing.module file, I have set up child routes along with an empty route for the default login page and a '**' route for handling 404 errors. Below is the code snippet: const routes: Routes = [ { path: 'dashboard' ...