Dealing with CORS: Troubleshooting the 'Access-Control-Allow-Origin' issue when a NextJS app deployed on an Nginx server attempts a GET request to a local Express server

While everything worked fine on my local machine, I encountered an issue after deploying to my droplet with nginx/1.18.0 and certbot for HTTPS. The error occurred when attempting a GET request from my NextJS app (localhost:3000) to an express route specified in my npm script:

"node_1": "nodemon --watch dev -e js dev/networkNode.js 3001 http://localhost:3001"

The specific error message was:

Access to XMLHttpRequest at 'http://localhost:3001/blockchain' from origin 'https://chalkcoin.io' has been blocked by CORS policy...

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

I attempted various solutions such as adjusting the corsOptions to origin: "https://chalkcoin.io" and origin: "*" for app.use(cors(corsOptions)). Additionally, I tried removing the http:/https: protocol from the axios request URL in Blockchain.Context.js.

I also experimented with adding

<meta httpEquiv="Content-Security-Policy" content="upgrade-insecure-requests"></meta>
within the <Head> component of _app.js.

This led me to ponder the ideal approach for running my npm command for node_1 using pm2 in the background while keeping my Nextjs app active on localhost:3000.

Express backend (localhost:3001):

Code snippet below:

[insert provided Express backend code snippet here]

Blockchain.Context.js:

Another code snippet exists for Blockchain.Context.js:

[insert provided Blockchain.Context.js code snippet here]

/etc/nginx/sites-available/config

An excerpt from the configuration file:

[insert provided Nginx configuration snippet here]

Answer №1

After successfully resolving the issue for Firefox and Chrome, I encountered difficulties with Safari. The CORS error in Firefox and Chrome was due to a mismatched CORS header value. To fix this, I replaced string interpolation with a regular string in the axios.get request and included CORS options in the express app file.

const getNode1 = "http://localhost:3001/blockchain";
const res = await axios.get(getNode1);
const corsOptions = {
    optionsSuccessStatus: 200,
    credentials: true,
    origin: "https://chalkcoin.io",
};

const app = express();

app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

I suspect that the use of string interpolation led to this error as CORS does not support wildcards. However, I am still unsure why Safari is presenting this issue. Could it be related to the mix of HTTPS domain and HTTP request?

If you need additional information, you can refer to this https://i.stack.imgur.com/oqudW.png.

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

Unable to get custom named local strategies functioning correctly in PassportJS

Recently, I found the need to modify our local strategy in order to accommodate different types of users logging into our website. The current code is as follows: const localLogin = new LocalStrategy(localOptions, function(email, password, done) { // V ...

The deployed NextJs app on Vercel is not displaying proper Tailwind CSS styles

I'm experiencing issues with the tailwind styles on the deployed version compared to localhost. Here is my current tailwind config: module.exports = { mode: "jit", purge: [ "./pages/**/*.{js, ts, jsx, tsx}", "./co ...

Is there a way to make Forever write to a new log file on a daily basis?

I am managing a group of production servers that run a Node.JS application using Forever. It seems like my current log file options are limited: Allowing Forever to handle logging on its own, resulting in logs being saved to ~/.forever/XXXX.log Specifyin ...

I am encountering an issue where I am using Getserversideprops within a page to retrieve data from Strapi, but I am consistently

Having an issue with fetching data from a Strapi backend using getServerSideProps in Next.js. The data appears to be undefined, even though the link works correctly in the browser. I am fetching inside a page, not a component, following the method descri ...

Implementing unique metadata tags for Next.js version 13

Can custom metatags be created with Next 13 and the ability to control if it should be labeled as "name" or "property"? I attempted to add Facebook metatags such as 'og:updated_time', but that specific key is not available. Using 'other&apo ...

How can you generate a Ref in React without utilizing the constructor by using React.createRef?

In the past, I relied on using constructor in React for just three specific purposes: 1. Initializing state as shown below: class App extends React.Component { constructor(props) { super(props); this.state = { counter: 0 }; } } H ...

Having difficulty getting React set up with create-react-app

Recently, I delved into the world of React and decided to hone my skills by setting up Node 12, which automatically installed npm. After creating a folder named "reacthello", I entered the command "npm -i" followed by "npm i -g create-react-app". However ...

Controlling flow with Middleware in ExpressJS using Router.param() & Router.use()

Within my Express.js application, I have integrated custom validations and parameter parsing. Specifically, one of my routes requires the obj_id to be included in the route. In cases where mongoose cannot locate an object with that ID in the database, a 40 ...

What are the steps for containerizing a Vue.js application?

When attempting to access the site locally through on Chrome, I receive an error message stating "172.17.0.2 took too long to respond". To retrieve the IP address of the container, I used the inspect command. docker inspect -f '{{range .NetworkSett ...

React Syntax: code that doesn't require the use of <div> tags

Is there a way to refactor my code so that I don't have to use a div wrapper? { allItems.map(item => ( { item === 2 && <li className="page-item"> <span className="page-link">...</span> </li> } &l ...

Error: Reactjs - Attempting to access the 'name' property of an undefined variable

As I continue to learn about React, I have been experimenting with props in my code. However, I encountered an error where the prop is appearing as undefined. This issue has left me puzzled since I am still at a basic level of understanding React. If anyo ...

The Heroku application is experiencing crashes

After mastering node.js, I decided to deploy my project on Heroku. However, upon deployment, Heroku started throwing error messages that have left me puzzled despite logging and analyzing the errors. Below are the detailed logs: 2016-04-13T14:24:17.24868 ...

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 ...

Check for data with Sequelize and update it if found

Looking for a way to determine the existence of data in sequelize, I am in need of updating it. Utilizing models.Booker.findAll with the booker id allows me to search for the data by its unique identifier. If the result is greater than 0, then I proceed to ...

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 ...

Next.js causing error during Chakra UI Integration

Currently, I am trying to set up Chakra UI (latest version V1) with a basic Next.js application. After following the instructions in the 'getting started' guide on , I encountered an error while running the development server: Error - ./node_modu ...

Display additional images with "Show More" view

I'm looking to create a view similar to the one shown in this image: https://i.stack.imgur.com/AZf61.png Within my FlatList, all the data is being populated including these thumbnails. These thumbnails are stored in an array of objects where I retri ...

Issue encountered during deployment of node.js app to Heroku - files appear to be structured correctly, but experiencing buildpack error?

Encountering an error while deploying a node.js app on Heroku, where the buildpack couldn't detect a node.js codebase as shown in the screenshot below. I have set the build pack and ensured that the package.json is at the root level along with the ap ...

Is there a way to determine the bounding rectangle of a specific word within a paragraph when you only have its index?

I am currently developing a text-to-speech functionality for a react application that can emphasize the word being spoken by highlighting it with a background color. This feature closely resembles the layout of the Firefox reader view. However, my curren ...

I wonder what might be the root of this Heroku crash with error code H10

After reviewing previous suggestions regarding this issue, such as restarting dynos or ensuring the use of var PORT = process.env.PORT || 3000, I have implemented all of these solutions but my application continues to crash. The app is built using node/exp ...