Encountering an undisclosed CORS error on all requests from Angular frontend to NodeJS Express Server during preflight 200

After thorough testing with Postman, my backend server is functioning properly and generating the desired responses for all requests.

However, my Angular app is encountering an unknown CORS error on every request despite receiving a 200 Preflight response. I have verified that the app is correctly configured.

The issue appears to be related to the absence of an origin header in the final requests, but I am unsure why this is happening.

This is the Express CORS implementation:

app.use((req, res, next) => {
    const actualOrigin = req.headers.origin;
    if (originArray.includes(actualOrigin)) {
        res.setHeader('Access-Control-Allow-Origin', actualOrigin);
    } else {
        return res.status(403).send('Unauthorized Origin');
    }
    res.setHeader(
        'Access-Control-Allow-Methods',
        'GET,POST,PATCH,DELETE,OPTIONS,PUT'
    );
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
});

Example frontend request:

async login(data) {
    console.log('data is: ', data);
    let sendData = {};
    if (data.loginType === 'slot') {
        sendData = {
            username: data.username,
            password: data.password,
            type: data.loginType
        };
    } else if (data.loginType === 'user_name') {
        sendData = {
            username: data.username,
            password: data.password,
            type: data.loginType
        };
    }

Inspected request:

auth.service.ts:275 Error occurred during login: HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'http://localhost:3000/ibescore/auth/login', ok: false, …}

Preflight request details:

Request URL:
http://localhost:3000/ibescore/auth/login
Request Method:
OPTIONS
Status Code:
200 OK
...

Actual request details:

Request URL:
http://localhost:3000/ibescore/auth/login
...

Answer №1

It would be beneficial to utilize the cors npm package for handling common issues, allowing you to concentrate on enhancing your app's functionality.

To install, run the following command:

$ npm install cors

After installation, implement it on the server by adding the following code:

var express = require('express')
var cors = require('cors')
var app = express()
 
app.use(cors())

Answer №2

Expanding on the solution provided in this answer, incorporating a custom corsOptions has successfully resolved the issue at hand.

The origin property functions by taking the request origin and a callback as parameters. It checks if the request origin is present in the originArray or if the origin is undefined. If either condition is met, the callback is triggered with null as the first argument and true as the second argument to indicate permission for the request. Conversely, if neither condition applies, an error object is passed as the first argument to deny the request.

const corsOptions = {
    optionsSuccessStatus: 200,
    origin: function (origin, callback) {
        if (originArray.includes(origin) || !origin) {
            callback(null, true);
        } else {
            callback(new Error('unauthorized Origin'));
        }
    }
};

app.use(cors(corsOptions));

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

Angular is throwing a RangeError due to exceeding the maximum call stack size

Encountering a stackOverflow error in my Angular app. (see updates at the end) The main issue lies within my component structure, which consists of two components: the equipment component with equipment information and the socket component displaying conn ...

There seems to be an issue as req.files in Sails.js is blank and the value of req

I've been struggling with this problem for quite some time now. Despite my efforts to find a solution through Google and StackOverFlow, I have not been successful. The issue lies within a project I am working on, where I have implemented a "Product" M ...

Can a single endpoint provide various JSON responses depending on the user's role?

I seem to be facing a terminology confusion which may be hindering my ability to find a solution. My current project involves creating a REST API within Express and I intend to incorporate roles in the authorization process. What I am curious about is whet ...

Encountering difficulty reaching the web server while attempting to dockerize Hapi JS

I have been working on a web application using the Node JS web framework, Hapi JS. Unfortunately, I am facing some issues with dockerizing my application. My process began by setting up npm for the project with the command: npm init I then proceeded to ...

Error: Attempting to access the property 'cinemaName' of an undefined object

I am brand new to using angular2 and higher. My form definition with an input field of type text looks like this: <form class="form-horizontal" name="form" role="form"> <div class="form-group"> <label class="col-md-3 co ...

Interpreting user input from the terminal with Node.js

Having an ssh2 server, I aim to extract the entered commands and parse them. Presently, I am relying on the readline module for this task. However, it tends to output special characters when backspace is used. My intention is not to capture every keypress ...

Launching a Node.js application automatically on startup with Ubuntu, Vagrant, and Puphpet

I have recently configured a node.js app on an Ubuntu environment using Vagrant/Puppet (generated from puphpet.com). Now, I need to send the finalized package to someone and ensure that the node.js app automatically starts running once they finish executin ...

Angular 2 testing error: Unable to connect to 'ngModel' as it is not recognized as a valid property of 'input'

Currently, I am experimenting with angular2 two-way binding for the control input. Below is the issue that I encountered: An error occurred: Can't bind to 'ngModel' since it isn't a known property of 'input'. Contents of app. ...

What could be causing the 404 error message in Backend deployment on Vercel?

Hello everyone, I'm currently in the process of deploying the backend for my MERN application on Vercel. Prior to this attempt, I successfully deployed a small todo project using MERN on Vercel. Everything worked fine then, and I followed the same st ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

Using handlebars to access the current URL in a NodeJS application

Looking for the most effective method to acquire the current URL in order to insert a unique ID for a div tag. Specifically working with keystone.js framework. For example, (if page == index) { "page--index-" } ...

Error message saying 'Callback has already been invoked' returned by an async waterfall function

I'm facing an error that I understand the reason for, but I'm unsure how to resolve it. Here's a breakdown of my initial function: Essentially, I am making a get request for all URLs stored in the database and then, for each URL response, I ...

Is it possible to transfer parameters from one page to another page using the pop method in Ionic 2?

Is it possible to pass parameters from one page to another during a push operation, but how can this be done during a pop operation? showfilter(){ this.navCtrl.push(FilterPage,{ fulldetail : this.selectedarea }); } Can you explain how ...

Manipulating a Stepper Motor using an Arduino and Node.js

I have successfully set up my stepper motor using an L293d driver connected to an Arduino. The instructions I followed can be found at this link: . I modified the code provided in the tutorial, originally meant for a DC motor, to work with my stepper motor ...

Access the configuration file within the "scripts" section of the package.json file

Is there a way to configure a custom port for the "serve" script in package.json by reading from a config file? Context: Our team of developers is working on the same terminal server. In our package.json file, we have the following section: ... "scripts" ...

Build an Angular wrapper component for the phone textbox functionality

Looking to transform the Phone Mask solution below into an Angular component. Does anyone have a method to accomplish this? * Any solution that results in a similar component for a Phone textbox will suffice. Mask for an Input to allow phone numbers? ht ...

Angular 4 Web Application with Node-Red for Sending HTTP GET Requests

I am creating a unique service that utilizes Node-red to send emails only when a GET request is made to 127.0.0.1:1880/hello (node-red port), and an Angular 4 web app (127.0.0.1:3000) for client access. Upon accessing the /hello page from a browser, I rec ...

Module ‘gulp’ could not be located

Whenever I try to execute the ionic build android command, it keeps showing me an error message: WARNING: ionic.project has been updated to ionic.config.json, so you need to rename it. Oops! It seems like there's a missing module in your gulpfile: Mo ...

Displaying Child Component in Parent Component After Click Event on Another Child Component: How to Implement Angular Parent/Children Click Events

After delving into Angular 7 for a few weeks, I find myself faced with the challenge of toggling the visibility of a child component called <app-child-2> within a Parent component named <parent>. This toggle action needs to be triggered by a cl ...

Allow Nest.js server to receive binary files in the request body

Is there a way to retrieve the uploaded binary file data from the browser? While the Nest.js server application functions correctly with Postman, it throws a 400 error when the request is sent from the Google Chrome/Angular application. Any ideas on how ...