Testing the connection between my local React frontend and Node.JS server
P粉327903045
P粉327903045 2023-09-07 17:14:04
0
1
364

I created a node.JS Express server that does the job of sending JSON to my frontend using the API. I completed the backend and put it on an AWS server. Now I just want to work on the React frontend. I start react on localhost:3000 and make a request to an AWS server, but I get a CORS error telling me that localhost:3000 does not have permission to send requests to that server.

Access to "http://www.myawssever.fr:4000/api-url/" from source "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 meets your needs, set the request mode to "no-cors" to get the resource with CORS disabled.

I've tried multiple solutions to authorize localhost:3000 but I don't think the problem comes from there, because to the server localhost:3000 is the address itself! Do you know how I can test my back from my computer (React on localhost:3000) by sending a request to the server (AWS)?

P粉327903045
P粉327903045

reply all(1)
P粉077701708

Here are the combined steps to resolve CORS errors and enable communication between the React frontend and the AWS server

Configuring CORS on your AWS server

First, you need to configure your server to include the appropriate CORS headers in the response . You need to add the "Access-Control-Allow-Origin" header with the value "http://localhost:3000" to allow requests from your React application.

Specific method to configure CORS

The exact method of configuring CORS depends on the server technology you are using (e.g. Express, Apache, Nginx). For example, if you use Express, you can use the cors middleware. Here is an example of how to configure CORS using Express:

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

const app = express();

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

// Rest of your server code...

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

Restart your AWS server

After configuring CORS, restart the AWS server to apply the changes.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!