Exploring the Connection Between Express.js and CORS

I developed a frontend using react.js and an API server using express.js. To handle CORS, I utilized the cors package as shown below:

var passport = require("passport");
const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors());
app.use('/route1', passport.authenticate('jwt', {session: false}), route1)
app.use('/route2', passport.authenticate('jwt', {session: false}), route2)
app.use('/route3', passport.authenticate('jwt', {session: false}), route3)

app.use(function(req, res, next) { /* catch 404 and forward to error handler */
  next(createError(404));
});

app.listen(app.get('port'), () => {    
  logger.info('Server started')
})  

All routes function correctly, except when multiple requests are made consecutively for the same route. For instance:

POST example.com/route1
GET example.com/route1

When this occurs, I receive the error

No 'Access-Control-Allow-Origin' header is present on the requested resource.
in the browser console for the GET request. However, if I modify the paths of the routes, like so:

POST example.com/route1
GET example.com/route1/example

it functions properly.

Both servers are hosted on an apache webserver. The backend server is accessed via https, which redirects it to the nodejs server operating on http.

What am I missing? Thank you.

edit: here is a snippet of route1:

const express = require('express')
const router = express.Router()
const errors = require('./error_handler');

router.post('/', async (req, res, next) => {
    const result = 
        /* DB Middleware */
        .catch((err) => errors.errorHandler(err,res))

    if(!res.headersSent) /* Adding this condition to check if errorHandler() already sent an error response */
        res.send(result);
})

router.get('/', async (req, res, next) => {
    if(req.query.course === undefined)
        res.send(400);  


    let result =
        /* DB Middleware */
        .catch((err) => errors.errorHandler(err,res))

    
    if(!res.headersSent)
        res.send(result)
})

module.exports = router

Answer №1

A little while back, I encountered a similar issue in one of my projects. I found a solution that worked for me by allowing every origin to access the project.

app.use(function (req, res, next) {
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);
    // Pass to next layer of middleware
    next();
});

If this doesn't work for you, consider adding crossDomain to your request like so:

 $.ajax({
    url: url,
    crossDomain: true,
    data: form,
    dataType: 'json',
    success: function(data) {
        console.log(data);
    },
    type: 'POST'
});

Answer №2

To implement CORS in your application, add the following code to app.js:

var express = require('express')
var cors = require('cors')
var app = express()
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}
app.use(cors(corsOptions));

You can also create a common middleware to enable CORS for any API endpoint:

var AllowedOrigins = ['http://example1.com', 'http://example2.com'];
setCorsHeaders: function (req, res, next) {
    let requestDomain = req.headers.Origin;
     AllowedOrigins.forEach(allowedOrigin => {
         if (requestDomain === allowedOrigin) {
            res.setHeader('Access-Control-Allow-Origin', requestDomain);
            res.setHeader('Access-Control-Allow-Credentials', true);
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
         }
     });
     if (req.method === 'OPTIONS') {
        res.status(200);
     } else {
        next();
     }
}

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

What is the best way to activate a post function using a hyperlink?

I'm struggling to figure out how to call my post function using a link within my navbar. The issue is that I'm working with links in the navbar code, and not sure how to integrate calling the post function with them. Below is the code for my pos ...

Encountering a Node.js error while working on a Telegram bot project

http://prntscr.com/jo7mug This showcases an error scenario where my bot responds twice, which is not the intended behavior. The code structure involves prompting the user to choose between a file and a link, followed by selecting a style. However, upon se ...

Stopping Socket.io listener once it has been triggered

I am trying to set up a listener on a socket that will automatically stop listening once it has been executed. I came across this post on Stack Overflow: socket.io Removing specific listener However, I am having trouble figuring out how to actually make ...

Creating a critical section in a multi-instance Node.js application in a Kubernetes environment - a step-by-step guide

Recently, I encountered a situation where an interval is set up in Node.js to send periodic emails in a MEAN stack application running on multiple instances in a Kubernetes deployment. However, I noticed that the interval was triggered for all instances ...

The request body is not showing up as a key-value pair, while the request headers and other parameters are visible

Example of 'Advanced REST Client' Request I am currently using Postman and Advanced REST client to create a simple POST request based on the code below: 'use strict'; var express = require('express'); var bodyParser = requir ...

Error message: The specified file or directory does not exist and cannot be unlinked

fs.unlink('backup/' + 'test') An issue arises when attempting to delete a folder: { [Error: ENOENT: no such file or directory, unlink 'backup/test'] errno: -2, code: 'ENOENT', syscall: 'unlink', p ...

Here's a unique version: "Sharing data between functions in the Express GET API within MEAN Stack"

Within my code, I have a function called hsResponse which operates as described below. When I run this function independently, I am able to see the expected body response in the console log. Now, I would like to incorporate this hsResponse function within ...

GULP showing an error message "ACCESS DENIED"

Exploring the fascinating realm of Gulp for the first time has been quite an adventure. I have managed to create a gulpfile that effectively handles tasks like reading, writing, and compiling sass/css/js/html files. However, when I try to access the site o ...

Options or menu in Whatsapp-Web.js

I am currently working on creating an app using node.js with the goal of sending WhatsApp messages to my client list. To achieve this, I am utilizing WhatsApp-Web.js. While I have successfully included media messages and text captions, I am encountering d ...

What steps should I take to create code that can generate a JWT token for user authentication and authorization?

I'm struggling to get this working. I have a dilemma with two files: permissionCtrl.js and tokenCtrl.js. My tech stack includes nJWT, Node.js/Express.js, Sequelize & Postgres. The permission file contains a function called hasPermission that is linke ...

JavaScript - memory heap exhausted

Recently, I encountered an issue with my API written in Node.js. The purpose of this API is to read data from a MySQL database, write it into a CSV file, and allow users to download the file once the writing process is complete. Initially, everything was f ...

Sorry, but I cannot install expo dependencies at this time

I am currently using nvm to switch between node versions 4.4.3 and 12.14.1. After switching to version 12.14.1, I tried to install expo and run a react-native project following the instructions here. npm install -g expo-cli expo init npm start However, w ...

I'm currently attempting to set up the React JS package, but unfortunately encountering some errors in the process

I'm having trouble installing react as I keep receiving errors. My system has npm version 8.12.1 installed. I attempted to downgrade react, but that didn't resolve the issue. I tried the following steps: Update npm using: npm install npm -g Dow ...

Can the flow of code in NodeJs be disrupted by throwing an Exception in Javascript?

Is there a way to achieve similar functionality in NodeJS as in Java? I have a code snippet that checks for redundant documents and raises an exception if one is found. However, I want the exception to interrupt the code flow and prevent further execution. ...

Memory leaks observed in BinaryJS websockets

Currently, I am in the process of developing a simple client/server setup to facilitate the transfer of image data between a browser and a node.js server using BinaryJS websockets. Despite following the API examples closely, it seems that my implementatio ...

Why is my host address not being recognized by nodejs v5.10.1 anymore?

Why is the latest version of Node.js (v5.10.1) no longer able to retrieve my host address? Here's the Express code snippet: var express = require('express'); var app = express(); // Respond with "Hello World!" on the homepage app.get(&apo ...

Encountered an error while trying to update the Node Package Manager using the command: `npm install npm@latest -

Recently, I attempted to update my Node Package Manager by using the command g npm install npm@latest -g in the terminal. However, upon checking if the update was successful with commands such as npm --version, npm -v, or even npm install, I encountered th ...

What causes the error message "TypeError: client.db is not a function" to appear in Node.js and what steps should be taken to resolve it?

Struggling with writing a MongoDB aggregation query in Node.js. Despite my best efforts, the codes I implemented are not working as expected and throwing the error: TypeError: client.db is not a function const { MongoClient, ObjectId } = require(' ...

Implementing Array Declaration and Validation in a POST Request

Validation of missing fields in the post method is crucial for my project. The structure of my table includes fields such as: { name: string, required: true products: [ { name: string, required: true quantity: number, required: true ...

Fetching items from a MongoDB collection using an array of unique identifiers

Creating an API using node.js/express and MongoDB. I have two collections that are related in a many-to-many way, Users and Items. My goal is to retrieve all the items that a user is following. Each user has an array of item IDs. How can I query to fetch ...