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

execute npm scripts concurrently

Seeking a simpler solution for managing pre-script hooks in my package.json file. Currently, I have multiple commands that all require the same pre-script to run. While my current implementation works, I'm wondering if there is a more efficient way to ...

Restricting the data type of a parameter in a TypeScript function based on another parameter's value

interface INavigation { children: string[]; initial: string; } function navigation({ children, initial }: INavigation) { return null } I'm currently working on a function similar to the one above. My goal is to find a way to restrict the initi ...

Using Svelte with Vite: Unable to import the Writable<T> interface for writable store in TypeScript

Within a Svelte project that was scaffolded using Vite, I am attempting to create a Svelte store in Typescript. However, I am encountering difficulties when trying to import the Writable<T> interface as shown in the code snippet below: import { Writa ...

How should one handle the potential risks presented by literal types?

As I was translating a large JavaScript project into TypeScript, something caught my attention. Consider a module that looks like this: WinConstants.ts export = { "no_win":0, "win":1, "big_win":2, "mega_win":3 } I wanted to make it truly constan ...

Having difficulty constructing a full stack application using Express

I've been struggling to configure a full stack app using create-react-app with Express and TypeScript. My main issue is figuring out how to compile the server files into a build folder. I have separate tsconfig files for the server and create-react-ap ...

Unable to perform Undo function in monaco editor

Currently in my Angular 7 project, I have integrated the Monaco editor for coding purposes. One issue I am facing is that when I make a change to the code and then press ctrl+z to undo it, the previous code is successfully restored. However, if I change th ...

Extracting a raw string from the parameters of ActivatedRoute in Angular 4

I've looked high and low for an answer to this, but couldn't find a solution. I'm passing a string in the URL like so: "localhost:4200/home/ABCD%2BrAD4Og%3D%3D". However, when I subscribe to the parameter or use snapshot, I get something dif ...

Exploring the power of Typescript and Map in Node.js applications

I am feeling a little perplexed about implementing Map in my nodejs project. In order to utilize Map, I need to change the compile target to ES6. However, doing so results in outputted js files that contain ES6 imports which causes issues with node. Is t ...

The Google Sign-in feature is unable to access the property 'load' due to being undefined

I'm currently working on implementing a Google Sign-in feature in an Angular application, but I'm encountering the following error: Cannot read property 'load' of undefined This was actually working perfectly just an hour ago, but n ...

The TypeScript rule in the project-specific .eslintrc.js file is not being applied as expected

Currently, I am following a tutorial on Ionic/Vue 3 which can be found here. However, when I try to serve the project, I encounter the following error: https://i.stack.imgur.com/k4juO.png It appears that my project-level .eslintrc.js file is not being ap ...

What is the best way to programmatically choose an option from a ng-select dropdown list?

My program displays a list to the user utilizing ng-select. This particular list is populated with various items: item 1 item 2 item N The user has two options when interacting with this list. They can either select an existing item or add a new one. If ...

Validation of Angular 5 forms for detecting duplicate words

I need help with a basic form that has one input. My requirement is to validate that the user does not input an existing word. If the user does enter an existing word, I would like to display a message below the input field saying "This word already exis ...

Dynamically Disabling Form Control in Angular 2

There is a basic form with two form controls that initially have required validation. In addition to the form controls, there is a button in the template. When this button is clicked, it triggers a change in the behavior of the form group. Both form contr ...

Encountering Invalid Chai attribute: 'calledWith'

I am currently in the process of implementing unit tests for my express application. However, I encountered an error when running the test: import * as timestamp from './timestamp' import chai, { expect } from 'chai' import sinonChai f ...

What is the best way to incorporate the "child_process" node module into an Angular application?

Trying to execute a shell script in my Angular application has been quite the challenge. I came across the "child process" node library that might be able to help me with this task. However, every attempt to import the library led me to the error message: ...

Encountering difficulties during the migration process from a JavaScript to a TypeScript React Component

I've encountered some challenges with configuring TypeScript in my project. Initially, I developed my application using plain JavaScript. However, eager to learn TypeScript, I decided to convert my JavaScript project into a TypeScript one. To achiev ...

ngx-bootstrap encountered an issue: TypeError - _co.openModal is unavailable as a function

Just starting out with ngx-bootstrap, I was attempting to create a modal using the instructions from this site : However, I encountered the following error: ERROR TypeError: _co.openModal is not a function Here are some code snippets: //app.component ...

Is the 'case' in a switch statement not treated as a typeguard by Typescript?

Here is a simplified version of the code I am working with: type Todo = { id: string; text: string; }; type Action = | { type: 'DELETE'; payload: string } | { type: 'CREATE'; payload: Todo } function reducer(state: Todo[], ...

Having trouble with downloading a zipped folder on the client side in an Angular and Node.js (MEAN) application

I am facing an issue with allowing users to download compressed folders from the server. I have successfully compressed the folder, however, when attempting to read the tar file and send it for download on the client side, the file is either corrupted or o ...

Dealing with side effects in react/redux: Best practices and tips

Trying to find the best way to integrate an async side-effects handler into my react/redux setup has been quite a challenge. In my react-router-driven application, all the main containers at root level are smoothly dispatching actions and receiving update ...