Cross-origin resource sharing (CORS) seems to be creating a barrier for the communication between my Angular

During the process of developing an Angular and NestJS app with NGXS for state management, I encountered a CORS error while serving my application. The error message in the console indicated:

Access to XMLHttpRequest at 'localhost:333/api/product-index' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

After researching potential solutions, I came across this informative article which provided insights on managing CORS in Angular applications. Upon examining the recommended configuration files, I noticed that the required settings were already in place. However, there was a mention of updating a `server.js` file, which led me to believe it corresponds to the `main.ts` file in Angular projects. Nonetheless, I was unsure whether modifications should be made to the `main.ts` file in my Nest app or the one in my Angular app, considering I am using a `nrwl nx` monorepo for both apps.

This is the content of my Angular app's `proxy.conf.json` file:

{
    "/cre8or-maker-backend": {
      "target": "http://localhost:3333",
      "secure": false,
      "logLevel": "debug"
    }
  }

Furthermore, this snippet represents the `serve` object within the `architect` object in my `angular.json` file:

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "cre8or-maker:build",
            "proxyConfig": "apps/cre8or-maker/proxy.conf.json"
          }

The aforementioned configurations had already been implemented in my project, leaving me puzzled about the directive to modify the `server.js` file (potentially analogous to Angular's `main.ts`). Here are the contents of my `main.ts` files:

nest main.ts

import { NestFactory } from '@nestjs/core';

import { AppModule } from './app/app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const globalPrefix = 'api';
  app.setGlobalPrefix(globalPrefix);
  const port = process.env.port || 3333;
  await app.listen(port, () => {
    console.log('Listening at http://localhost:' + port + '/' + globalPrefix);
  });
}

bootstrap();

angular main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.error(err));

Despite having installed the `cors` npm package, I remain uncertain about the additional steps needed to resolve the issue. Any assistance would be greatly appreciated.

UPDATE A couple of attempted fixes involved adding `app.enableCors();` and modifying the `create(AppModule)` function in my NestJs app's `main.ts` file with `{cors: true}`, which did not provide a solution. Additionally, incorporating the following code snippet yielded no success:

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Accept');
    next();
  });

As of now, I have defined one state that makes an API request to the backend. Inside this state, an action is structured like so:

@Action(GetProductIndexList)
    getProductIndexListData({patchState, dispatch, getState}: StateContext<ProductIndexListModel>){

       return this.dataService.fetchProductIndexList().pipe(tap((result)=>{
            const state = getState();

            patchState({items:[...state.items, ...result]});
        }));
    }

The API call is initiated within a service named `dataService`, configured within the state's constructor. Below is the structure of the service file:

@Injectable({ providedIn: 'root' })

export class ProductIndexService{

    constructor(private httpClient: HttpClient){}

    private readonly URL: string = 'localhost:3333/api';

    public fetchProductIndexList():Observable<CattegoryIndexItem[]>{
        const path: string = this.URL + '/product-index';

        return this.httpClient.get(path) as Observable<CattegoryIndexItem[]>;
    }
}

While the controllers in my NestJS setup work seamlessly, indicating proper setup, I am still encountering issues related to the CORS error. Should further details regarding my NestJS setup prove beneficial, kindly notify me and I will update this query with the relevant code snippets.

Answer №1

While working on an Angular 13 and Nest.js 8 app in an NX workspace, I encountered a CORS issue.

To resolve this problem, I successfully added the line app.enableCors(); in the main.ts file of my Nest.js application.

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    const globalPrefix = 'api';
    app.setGlobalPrefix(globalPrefix);
    app.enableCors();
    const port = process.env.PORT || 3000;
    await app.listen(port);
    Logger.log(
        `🚀 Application is running on: http://localhost:${port}/${globalPrefix}`
    );
}

Refer to the documentation:https://docs.nestjs.com/security/cors

Answer №2

After discovering my mistake of sending a request to localhost:333 instead of localhost:3333 in the service file, I was able to resolve the CORS error. However, there are still other errors that I have raised in a new question for further assistance.

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

"Create a separate function for the pipeable operator in RXJS for enhanced code

After working on some code, I came up with the following implementation this.form.valueChanges.pipe( take(1), map(val => // doSomething), exhaustMap(val => // someInner observable logic return of({someValue}) ) ).subscrib ...

What is the best way to programmatically generate a service within Angular?

Is there a way to dynamically create services at runtime using a string name (like reflection)? For example: let myService = new window[myClassName](myParams); Alternatively, you could try: let myService = Object.create(window[myClassName].prototype); m ...

When comparing the values of two arrays with undefined property values

Struggling with sorting an array of arrays that works perfectly except when the property value is undefined. Take this example: posts array = {id: "1", content: "test", "likes":[{"user_id":"2","user_name":"test"}] }, {id: "2", content: "test", "likes": ...

Utilize Angular 9 with an M1 Mac device

Struggling to get my project, which utilizes Node 12 and Angular 9, up and running on my new M1 Mac. I used nvm to install node and the latest npm version, then ran the command npm i -g @angular/cli@9 to install angular. Even though which ng confirms that ...

How can I retrieve a certain type of object property in TypeScript?

Imagine having a collection of flags stored in an object like the example below: type Flags = { flag1: string, flag2: string, flag3: boolean, flag4: number } // const myFlags: Flags = { // flag1: 'value 1', // flag2: 'value 1&ap ...

Ways to change information in a class variable using Angular

A sample registration application has been created and I am looking to store the data in a class data model. Below is the class model that has been created: export class Model { name: string; tableData: any[]; constructor() { this.tableData = [ ...

Encountering an error in Angular2 and TypeScript: TS2322 error message stating that the type 'Response' cannot be assigned to type 'UserStatus'

Currently, I am facing some challenges while working with Angular2 and TypeScript. Transitioning from AngularJS to Angular2 has proven to be a bit tricky for me. To better understand this new framework, I decided to create an experimental app with the foll ...

The Angular component seems to be failing to refresh the user interface despite changes in value

Recently, I created a simple component that utilizes a variable to manage its state. The goal is to have the UI display different content based on changes in this variable. To test this functionality, I implemented the component and used a wait function to ...

Tips for capturing a screenshot of the ESRI Map using Angular

Is there a way to capture a screenshot of the Esri map in its current state on the UI and then convert it into a PDF for download using Angular? Below is my current .ts code, but I am open to any additional suggestions. esri-map.component.html <!-- Map ...

Ways to set a default selection for an md-radio-button in md-radio-groups

My button group consists of 3 radio buttons for filtering data, and I would like to have a specific button selected by default when the page loads. Below is the code snippet: <md-radio-group ng-model="status" aria-label="filter" ng-model="status" name ...

When using Validators.pattern('^[0-9][0-9][0-9]$') in Angular 9, it does not validate numbers with a leading 0, such as 012

When attempting to validate a simple PIN with the possibility of leading zeros, I created this basic regular expression: ^[0-9][0-9][0-9][0-9][0-9][0-9]$ Although this regex worked fine on various online tools for testing regular expressions, it failed i ...

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...

Is it feasible to connect to an output component without using EventEmitter?

When it comes to creating components, I've found it quite easy to use property binding for inputs with multiple options available like input(). However, when dealing with component outputs, it can be a bit complicated as there's only one option u ...

Arranging an array containing three elements

As I work on my angular app, I have come across the following array: [ { "Name": "Jack", "IncomingTime": "2020-06-19T11:02+00:00", "Outgoingtime": "2020-06-19T11:07+00:00" ...

Creating a custom component in Angular 2 that includes several input fields is a valuable skill to have

I have successfully created a custom component in Angular 2 by implementing the CustomValueAccessor interface. This component, such as the Postcode component, consists of just one input field. <postcode label="Post Code" cssClass="form-control" formCon ...

Is it possible to use the Optimistic Hook with boolean values?

I am facing an issue with a switch component where the checked value is updated only after refetching the data when the user is changed to an admin status. Currently, there is a delay when clicking the switch as it takes time to load and then updates. It ...

Leveraging dependency injection in Angular 2+ with pre-loaded models

I desire the ability to create an instance of a model using a constructor while also providing injected services to that model. To clarify, I envision something like this: var book = new Book({ id: 5 }); // creates instance, sets id = 5 book.makeHttpCa ...

What causes TypeScript to be unable to locate declared constants?

I am facing an issue with the following simple code snippet: const getMethod = 'get'; const postMethod = 'post'; export type RequestMethod = getMethod | postMethod; When I try this code in TypeScript Playground, it shows an error sta ...

Typescript Regular Expression Issue: filter function is not returning any matches

Currently, I am developing an Ecommerce API and working on a class specifically for search queries. My approach involves using regex and typescript with node.js. Although I have based my project on a JavaScript node project, I am encountering an issue wher ...

Can a string input be converted to an HTML template in Angular 4+?

Is there a method to assess strings provided into a component's template as HTML? Here is the content I'm passing: export const BARS: Blurb = { title: "Bars", description: "blah blah blah. <a routerLink='/barcades'>Barcades& ...