简体   繁体   中英

NodeJs React Proxy - Backend Api Request

I am currently running a NodeJs with Express Framework and React as my frontend. When I make my request on the development machine the login (passport-google) works flawless. Since I added https to the production server it does not work anymore in google chrome but it is working in safari and IE.

I believe the request is not getting proxied to the express server.

"proxy": {
"/api/*": {
  "target": "http://localhost:3001",
  "secure": false
}

Proxy settings in react

This is the auth route

router.get(
  "/auth/google",
  passport.authenticate("google", {
    scope: ["profile", "email"]
  })
);

router.get(
  "/auth/google/callback",
  passport.authenticate("google"),
  (req, res) => {
    res.redirect("/dashboard");
  }
);

Thank you

Not sure how it could work in Safari and IE and not in Chrome, but understand that Create-React-App server does not exist in production.

If you are deploying to Heroku, everything changes. Before you deploy to production in Heroku you have to build your React project. When you build your React project, CRA takes all the JavaScript and CSS files and run Webpack and Babel over all those files and save a final build into a build/ folder.

When the user visits your application on Heroku, you are only running the Node/Express API and it sends the user back to the HTML file and the newly built JavaScript file placed in the build/ folder.

npm run build is what you would run before deploying to production.

So when you move into production, you just need to build the application, commit it, deploy to Heroku and you leave it up to the Express server to serve all the different JavaScript files.

So you only need to worry about the proxy for your development environment because CRA does not exist inside production.

You should be using relative routes in your React application.

The entire idea behind the proxy is to re-route requests from localhost:3000/auth/google to localhost:5000 because you are running the two servers in development so the API request has to be proxied, but when deployed you no longer make use of CRA, CRA only exists to use in development to help us create good quality React applications.

Localhost 3000 and 5000 cease to exist when you deploy to production in Heroku at least.

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