How to enable Access-Control-Allow-Origin for Angular 5 on the client side

I am currently utilizing the httpClient Angular package to make GET requests. The URL I am using to fetch data is , but I am encountering a CORS error in the console.

Unfortunately, I do not have access to the server side code, but I still want to enable CORS in my Angular service. Here is the function I am using:

myfunction() {
  let head = new HttpHeaders();
  head.append('Access-Control-Allow-Headers', 'Content-Type');
  
  head.append('Access-Control-Allow-Methods', 'GET');
  head.append('Access-Control-Allow-Origin', '*');
  
  return this.http.get("https://api.independentreserve.com/Public/GetValidPrimaryCurrencyCodes", {headers: head}).toPromise();
}

I experimented with the Chrome CORS extension and it worked fine. However, I would prefer to have CORS enabled within my Angular code.

I also attempted to implement proxies by following this tutorial. Nevertheless, it did not solve the issue. Below is the content of my proxy.conf.json file:

{
  "/api": {
    "target": "https://www.independentreserve.com/Public/GetValidPrimaryCurrencyCodes",
    "secure": false,
    "changeOrigin": true
  }
}

I added "start": "ng serve --proxy-config proxy.conf.json" to the package.json file, but this approach also failed to work. Does anyone have a solution for this problem?

Answer №1

The ability to modify response headers is limited to the server side and cannot be done on the client side. If you are unable to make changes directly on the server, your best option would be to introduce a proxy server under your control as an intermediary.

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

After submitting a multi-image form from Angular, the "req" variable is not defined

I'm currently facing an issue with submitting a form from Angular 7 to a Node backend using Multer as middleware and Express.json() as bodyParser. While the text data is successfully transmitted to the backend, the image fields are appearing empty {}. ...

Is there a way to make Typescript accept dot notation?

Is there a way to suppress the compile time error in Typescript when using dot notation to access a property that the compiler doesn't know about? Even though using bracket notation works, dot notation would be much more readable in my specific case. ...

AngularJS: Potential uncaught rejection encountered with the $http.get() method - Error Status: -1 due to CORS

Encountering an error while using a HTTP GET method: :63502/Scripts/angular.js:14525 Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","para ...

Angular 2 Final Router Encounters Error

I have implemented a basic router in my application to accommodate a URL structure like www.myhost.com/mission/myguid. I have reviewed the tutorials on the Angular site, but I haven't found any discrepancies. The "normal" routes such as www.myhost.com ...

Angular - Bootstrap 5 Slidehow is malfunctioning

I'm having trouble with the Bootstrap Carousel in Angular (17). The Previous & Next buttons don't seem to be working as expected. The carousel seems to be stuck on the first image and I'm not getting any errors in the console. I've ...

Using Angular and nativeElement.style: how to alter cursor appearance when clicked and pressed (down state)

I am working with a native elementRef CODE: this.eleRef.nativeElement.style = "_____?????_____" What should go in "???" in order to apply the :active style to the element? (I want to change the cursor style when the mouse is clicked down, not when it is ...

What sets apart `this.user.id` from `this.user = {id: ....}`?

I am puzzled by the error thrown in the code below: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-user', templateUrl: './user.compone ...

Creating a refined parameter type in Typescript using a discriminator

Looking to work with a legacy API that has the following structure (playground link)... type Command1 = { cmd: "my first command", arg1: string, arg2: boolean } type Command2 = { cmd: "my second command", foo: strin ...

Unable to access structuredClone on the global object within a Node.js application

structuredClone is causing issues in my NodeJS application. Whenever I try to utilize it, I encounter the error: structuredClone is not defined nodejs. To troubleshoot, I created a simple file and executed the following: console.log({ globals: Object. ...

Issue with Angular 7 and rxjs - Once catchError is triggered, the subscription stops receiving any further values

Consider the following code snippet: this.service1 .getValues() .pipe( mergeMap(response => this.service2.getMoreValues(response.id)), catchError(err => of({})) ) .subscribe(response) => { console.log(response) }); The issu ...

Issue with data not refreshing when using router push in NextJS version 13

I have implemented a delete user button on my user page (route: /users/[username]) which triggers the delete user API's route. After making this call, I use router.push('/users') to navigate back to the users list page. However, I notice tha ...

Tips for passing an object by value to an Angular2+ component

Imagine having a scenario where I create a component that takes a Foo instance and generates a form for editing. export class ChildComponent implements OnInit { @Input() foo : Foo; @Output() onChange : EventEmitter<Foo> = new EvenEmitter<Foo& ...

Stopping Angular2 HTTP Requests - A Guide to Aborting or Cancelling Executing Requests

Currently, I am implementing an autocomplete feature for my search functionality. handleKeypress(searchValue){ // Code to make an AJAX request with the search value // .... } I am looking to cancel any previous HTTP requests each time a keypress ev ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

What is the solution to the strict mode issue in ANGULAR when it comes to declaring a variable without initializing it?

Hi everyone! I'm currently learning Angular and I've encountered an issue when trying to declare a new object type or a simple string variable. An error keeps appearing. this_is_variable:string; recipe : Recipe; The error messages are as follows ...

The button values fail to adhere to the specified input length in the Point of Sale application built with Angular

Having an issue with my Point of Sale app. When I enter values using the keyboard, it respects the maxLength limit, but when I enter values using the buttons, it does not respect the limit. Any ideas on how to solve this? <div mat-dialog-content> < ...

The expiration date is not considered in JWT authentication using passport-jwt

I have been working on implementing an authentication system using JWT token in Express, utilizing passport-jwt and jsonwebtoken. Everything is functioning correctly at the moment, however, I am facing an issue where the token remains valid even after its ...

Struggling to destructure props when using getStaticProps in NextJS?

I have been working on an app using Next JS and typescript. My goal is to fetch data from an api using getStaticProps, and then destructure the returned props. Unfortunately, I am facing some issues with de-structuring the props. Below is my getStaticProp ...

Perform a series of database queries one after the other, ensuring they are completed before

Although the database queries themselves are working fine, I am facing an issue with executing them sequentially in Node. Here is an example of the queries I need to execute in order: DELETE FROM myTable; INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z); ...

Struggling to pass a method header to event handling in React markup

Within my render() method, I have a component with event handling capabilities. render() { ... <input type="text" onChange={(_) => { this.renew("email", _.target.value); }} /> } private renew(type: string, input: any) { ... if (typ ...