Encountering a cross-origin resource sharing (CORS) issue on NodeJS or Nginx server

After conducting thorough research on the topic following the formulation of this question, it has come to my attention that there are numerous queries similar to mine. However, I firmly believe the issue at hand here is distinct:

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

We encounter the Access-Control-Allow-Origin CORS error exclusively when initiating a substantial request:

Access to XMLHttpRequest at '.*****.es/xxxxxx' from origin '.*******.es' has been obstructed by the CORS policy: The requested resource lacks the 'Access-Control-Allow-Origin' header

All other requests function correctly, even though I attempted to configure:

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

without any success in resolving the error we're encountering.

I am beginning to suspect that the issue may be linked to nginx.

The current architecture we employ comprises of:

  • NodeJs, Expressjs
  • Middlewares:

    const LIMIT = '100mb'; const global = () => [ morganMiddleware(), compression(), cors(), bodyParser.urlencoded({ extended: true, limit: LIMIT }), bodyParser.json({ limit: LIMIT }), helmet(), ];

  • Server: Nginx 12.14.1

  • Hosted on AWS Elastic BeanStalk

If anyone possesses insights into what might transpire, ascertaining whether the root cause emanates from our nodejs server or nginx, kindly share your thoughts. We have explored several solutions and continue to investigate alternative avenues.

Answer №1

Find the version of Amazon Linux 2 (AL2) on your Elastic Beanstalk Dashboard:

https://i.stack.imgur.com/BJDqWm.png

Set up the following directory structure starting from the main directory of your App:

.platform/nginx/conf.d/

Create this specific file:

.platform/nginx/conf.d/01_custom_ngix.conf

Edit the client_max_body_size value within your newly created 01_custom_ngix.conf file (for example, 1000M = 1GB) and ensure your AWS Instance Type is at least t2.medium:

client_max_body_size 1000M;
client_body_buffer_size 100M;
...    
...    
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;

Commit your changes using Git.

Deploy your code:

> eb deploy 

options: eb deploy --verbose --debug

Answer №2

We have encountered an error on our server:

2020/02/20 10:56:00 [error] 2784#0: *127 client intended to send too large body: 4487648 bytes, client: 172.31.3.222, server: , request: "PUT /cars/drafts/f7124841-f72c-4133-b49e-d9f709b4cf4d HTTP/1.1", host: "backend.xxxxx.es", referrer: ""

In addition to the front-end error related to Access-Control-Allow-Origin, this issue is connected to a limit set in NGINX.

Our next step is to access our elastic beanstalk instance to adjust these variables, which we have already resolved thanks to the following guide:

SSH to Elastic Beanstalk instance

To rectify this problem, we need to create a file called x.config inside .ebextensions and update the variables using the provided yaml file:

files:
  "/etc/nginx/conf.d/01-client_max_body_size.conf":
    mode: 000644
    owner: root
    group: root
    content: |
      # MODIFIED VARIABLES ADDED BY 01-client_max_body_size.conf
      client_max_body_size 12m;
      client_body_buffer_size 16k;
container_commands:
  nginx_reload:
    command: sudo service nginx reload

After completing these steps, remember to redeploy your environment.

Many thanks for all the 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

Despite setting up express.static, Express.js is still unable to access static files

I attempted to access localhost:3000/index.html (where a static page is located), localhost:3000/javascripts/dio.js (where the JavaScript file is stored), and localhost:3000/images/dio1.jpg (where the images are housed). However, none of these resources ca ...

Troubleshooting: Issues with PassportJS JWT Strategy Integration with Node.js and MySQL

My app's authentication feature is causing me trouble. Every time I try to run my server.js file, I encounter the error "TypeError: Cannot read property 'fromAuthHeaderAsBearerToken' of undefined at Object." which prevents me from moving for ...

Some Firebase functions are being blocked by CORS policy restrictions

When working with FireBase cloud functions, I encountered a CORS policy error that only occurs with certain methods. For instance, my GET and POST requests work perfectly fine, but when attempting to delete or edit an object, the CORS policy error immediat ...

Guide to utilizing Angular for rendering views in Express

My goal is to utilize Angular for displaying the output page. What modifications need to be made in the default Express files? What should replace the following line of code: app.set('view engine', 'jade'); ...

Searching for an array of IDs in Mongoose

I have created an API using Express.js and mongoose to find users based on their ids in an array. // Here is the array of user ids const followedIds = follow.map((f) => f.followed); console.log(followedIds); // This will log [ '5ebaf673991fc60204 ...

Implementing single sign-on across different domains with an express server, react client, and redirect functionality

To tackle the challenge at hand, I am working on developing a web application that involves a form submission to my express server. The process includes generating a token from an external endpoint post using the form value, utilizing this token from an ex ...

How to showcase base64 encoded images in pug (jade) with node.js

Can anyone help with decoding this mysterious data and displaying the image? I'm using pug as my template engine. Below is the questionable data that needs to be shown as an image: /9j/4AAQSkZJRgABAQEAYABgAAD/4QBaRXhpZgAATU0AKgAAAAgABQ ...and so f ...

The process of passing a variable between two routes in an Express application

Is there a method to pass variables between two routes in expressJS without setting it as a global variable? For example, if we have the following routes: exports.routeOne = (req,res) => { var myVariable='this is the variable to be shared'; ...

Building a Full-Stack Application with React, Express, and Passport

I'm in the process of setting up a full-stack application that utilizes React and Express JS. For authentication, I have implemented Passport.js but encountered a minor issue... My front-end and back-end are running as separate packages on different ...

Having issues displaying the & symbol in HTML from backend data

I recently worked on a project using express handlebars, where I was fetching data from the YouTube API. However, the titles of the data contained special characters such as '# (the ' symbol) and & (the & symbol). When attempting to render the ...

Tips on recognizing the origin of incoming requests in a Node.js interface

In the development of my application using Node.js, Express.js, and Mongoose, I'm wondering how to determine if a request hitting my REST API service is coming from my front-end application rather than an unknown source. What steps or methods should I ...

What is the process for uploading an image with express-fileupload?

Looking to upload an image to Cloudinary via Postman using the express-fileupload library for handling multipart forms. Here is a snippet from my index.ts file: import fileUpload from "express-fileupload"; app.use(fileUpload()); In my controller ...

"Unable to locate the specified file or directory" error message pops up while attempting to save a file

Currently, I am in the process of generating a JSON file using my website with intentions to deploy it later. Below is the code snippet that I have implemented: saveFile = (i, data) => { var filename = `${i}_may.json`; var folder_list = ["desktop", ...

Requesting data from the application to the MongoDB database is currently malfunction

Currently, I'm utilizing Express and passport to develop an application. Everything has been going smoothly so far, but I've encountered a problem when attempting to retrieve data from my mongo database. Strangely enough, I am able to successfull ...

top-notch cloud option for handling JSON requests

I am currently developing an Android app that needs to access JSON data from three different websites at specific intervals throughout the day. In order to simplify this process, I am seeking a cloud solution that enables me to utilize scripting languages ...

Experience the power of SSR Nuxt.js with a seamlessly integrated REST API backend

Currently, I am working on developing a SSR Nuxt.js application that integrates with a REST API server. In order to achieve this, I have included my endpoint /api into the Nuxt server.js code as shown below: const express = require('express') c ...

Redirect all subdomains to corresponding folders with matching names

I am working on an Express app and I have the requirement to route each subdomain to its corresponding folder in the filesystem. To illustrate, when a GET request is made to example.com, it should look for files in the root folder ./, whereas blog.example. ...

What is the reason for needing to execute the "FLUSH HOSTS;" command daily in my project?

My project using a LEMP stack is currently hosted on Digital Ocean and I'm encountering an error: Host '167.71.227.200' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts' Every day, I have to use F ...

Avoiding the deployment of the test folder to the production environment within a node express application

Currently in the process of constructing a node express app, I have encountered a dilemma when shipping package.json to production. The issue lies in the fact that it includes code for unit testing as well. Is it advisable to create two separate package. ...

Having trouble fetching data (node.js) from my client (react.js)

I'm experiencing difficulty retrieving the data I send from the client to the server. Below is my react code: axios.post('http://localhost:5000/post-entry', { data: formData }) .then(res => { console.log(res); }) This is my server cod ...