Experimenting with a Node.JS server using my React front-end on my local machine

After successfully setting up my node.JS Express server to send JSON data from an API to the front-end, I deployed it on an AWS server. Now, I am focusing on developing the React front end of the project. However, when I try to make requests from localhost:3000 to the AWS server, I encounter a CORS error stating that the origin is not authorized.

Access to fetch at 'http://www.myawssever.fr:4000/api-url/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have attempted various solutions to whitelist localhost:3000 but suspect that the issue lies elsewhere since for the server, localhost:3000 is the source address itself! How can I effectively test my back end (AWS server) locally from my computer where React is running on localhost:3000?

Answer №1

Follow these steps to resolve the CORS error and establish communication between your React front end and AWS server

Setting up CORS on your AWS Server

To begin, make sure your server is configured to include the necessary CORS headers in the response. Add the "Access-Control-Allow-Origin" header with the value "http://localhost:3000" to allow requests from your React application.

The process for configuring CORS

The specific method for setting up CORS will vary depending on the technology used by your server (e.g., Express, Apache, Nginx). If you are using Express, you can utilize the cors middleware. Here is an example of how to configure CORS with Express:

const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors({ origin: 'http://localhost:3000' }));

// Additional server code...

app.listen(4000, () => {
  console.log('Server running on port 4000');
});

Restarting your AWS server

Once CORS has been configured, restart your AWS server to implement the changes.

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

The Node.js Express application that utilizes the fast-csv stream parser is unable to redirect when encountering "data-invalid" errors

A new tool is in the works to streamline the process of uploading CSV files into a database and presenting the data in various formats. The current issue at hand involves an error message that pops up when attempting to upload a faulty file with 6 columns ...

Guide on setting up various functionalities for a single route with Express Swagger Generator

Currently, I am utilizing the npm package called express-swagger-generator. When defining two routes as shown below: /** * @group Users - operations about user * @route GET /users * @route POST /users */ The issue arises where only the POST route is ...

Tips for Building a Dual-Column Form Using React Material-UI

Currently, I am in the process of creating a react form using material-ui. The main goal is to design the form with a fixed 2 column layout that does not adjust based on the browser size. The desired structure should always appear like this: |First Name ...

What causes the discrepancies in folder structure between Hexo in development and production environments?

I'm a beginner when it comes to nodejs and I have a question about a blog system built in nodejs called hexojs. The file structure for this blogging framework during development looks like this: https://i.stack.imgur.com/VdWbF.png, The main source c ...

Every time I use my NodeJS MySQL Query function, the results I get are never

Working on a new gaming project involving MySQL for multiplayer functionality. Issue arises when requesting specific queries, where the system retrieves incorrect data or results from previous queries. dat("SELECT * FROM server1;"); Misdirected queries r ...

Passing an event from onSubmit in React without using lambdas

Within our current project, the tslint rule jsx-no-lambda is in place. When attempting to capture event from onSubmit, this is how I typically write my code: public handleLogin = (event: React.FormEvent<HTMLFormElement>) => { event.preventDe ...

FormData: The formData does not contain any data and is displayed as an empty object

I am currently working on setting up a contracting, building, and construction company. As part of this project, I need to create an invoice by sending a request to the backend. The format of the request should match the details shown in the following imag ...

Inject an HTML or jade webpage into a div within another HTML or jade webpage

I'm facing an issue in my Node.js project with a script (JS) that is responsible for loading a Jade page into a div of another Jade page using $("#div").load(directory). Despite specifying the directory of the jade page to be loaded, I keep getting an ...

Converting a string parameter into a JSON stringified object in Express.js

Struggling with creating a query parameter to stringify a JSON object. Does anyone have any tips or solutions? ...

Unusual express middleware usage in NodeJS

app.use(function(req,res,next){ console.log('middleware executed'); next(); }); app.get('/1',function(req,res){ console.log('/1'); res.end(); }); app.get('/2',function(req,res){ console.log('/2'); res.end() ...

Utilize State Hooks with arrays and objects

***I'm looking to define the initial state as an array with two objects, each containing another array. However, I'm having trouble setting this state using setState. The state I am trying to set should consist of two objects, each with two prop ...

While loop not yielding immediate result with asynchronous function

As a beginner in Node.js, I have successfully connected an LCD Panel and a 4x4 Membrane matrix keypad to my Raspberry Pi. Using Node.js, I have programmed them to work together. My goal is to have the LCD panel immediately display any key pressed on the ke ...

The asynchronous/await methods within a loop for connecting to multiple servers through ssh2 are not functioning as expected

I'm working on a tool that interacts with multiple servers using the npm library ssh2. My goal is to automatically make changes to a specific file on all these servers by looping through them. Below is a snippet of the code I have been working on: co ...

What is the best way to align a Fab button within a circular progress indicator?

I'm attempting to center a FAB inside a circular progress bar. The suggestion was to use relative positioning for the parent and absolute positioning for the children. My goal is to maintain responsiveness, so that it looks consistent even when the sc ...

Saving a PDF file in Node.js using Express and Multer

Currently, I am utilizing a multer api to save files in memory. This is necessary because I have a requirement to upload both images and pdf files, with the added need to process the images. So far, I am able to successfully upload images, however, I am e ...

Having trouble changing text color in NextJS with Tailwind CSS?

Within my NextJS application, I have utilized an <h1> tag for the text and enclosed it in a <div>. However, despite my attempts to add color styling to the text, it does not seem to take effect. I even included it in my global.css file, but it ...

Tips for resolving the issue of 'no serverless pages built' during deployment of a Next.js application on Vercel

Recently, I've been encountering the same two errors while trying to deploy my NextJs app: // and will just error later on Error: No serverless pages were built. You can learn more about this error here I'm stuck and unsure of how to resolve bo ...

Click on the link within the Checkbox label on MUI

I am working on creating a checkbox for the "Terms of Use," using FormControlLabel to nest a Checkbox. However, I also need to include a link that opens a Dialog component displaying the terms. The challenge is that clicking on the link checks the checkbox ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

What is the best way to display JSON data in a readable format?

I received a JSON file with the following structure: { "data":{ "uuid":"123", "name":"TestData", "alias":null, "created_at":"2021-03-17T11:57:29.000000Z&q ...