简体   繁体   中英

What is the best way to connect React js app with node js server?

I have built and tested my ReactJS app and NodeJS server. React app has a sign-in form whose data I want to send to the server and get web tokens from there. I am using Axios to send it by the following code:

  const sendData = (e) => {
    e.preventDefault();
    axios
      .post(url, data)
      .then((res) => console.log("Data send" + data))
      .catch((err) => console.log(err));
  }; 

but I got this error in Brave Browser

Access to XMLHttpRequest at 'http://localhost:3000/api/v1/users/signup' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Please tell me is this the best practice? If yes, how to get rid of this error, and if not, what is the better way?

What you have here is a Cross Origin Resource Sharing (CORS) error due to the fact that your frontend is sat on one URL (for example localhost:3000) and your backend server is sat on another URL (for example localhost:5000). Browsers have this feature for security purposes as a way to only allow request from the same URL to be performed.

The solution for such an error lies on the server, and a way to control it, you'd need to configure it with this package

In expressjs, you could use the package as follows:

const express = require('express')
const app = express()
const cors = require('cors')
 
app.use(cors())

You can also pass arguments to the cors middleware if you want a specefic url to access your backend, otherwise if you leave it empty it means that any URL has the right.

app.use(cors({
 origin: "http://yoururl"
}))

You can check the documentation for more details.

I hope this geeksforgeeks detailed explanation link will help you for the same - -

https://www.geeksforgeeks.org/how-to-connect-node-js-with-react-js/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM