简体   繁体   中英

Setting up react and nodejs servers on same machine

I am setting up a reactjs application on port 3000 as well as a nodejs API server on port 3500 on the same box on the internet. Assume the box has a domain name example.com, and I am using nginx in reverse proxy to receive the end users over https, and internally direct it to the port 3000 of the reactjs server. On the react code, while calling axios API for a get command, which of the following should I be using:

Few tests I did:

  • Access from my browser the reactjs application successfully as example.com (nginx does the mapping to port 3000)
  • Using https://reqbin.com/ I was able to access the nodejs server API and get the correct result using: http://example.com:3500/users
  • Using https instead of http causes an error: SSL connection error Error code: 10035

If end user is supposed to connect over https to the react server, then the react server as well as the nodejs server should be running in https mode, or the browser will block the request and it will never reach the server. Here is how to:

  • Run the react server in https mode:
  1. Change nginx reverse proxy configuration to be:

         proxy_pass https://localhost:3000;

  1. Changed the URL for the nodejs server that axios is calling from http://localhost:3500 to https://example.com:3500

  2. After npm run build, and upload the build directory to the server, run the following commands:

su
serve -s build --listen 3000 --ssl-cert "/etc/letsencrypt/live/example.com/fullchain.pem" --ssl-key "/etc/letsencrypt/live/example.com/privkey.pem"
  • Run the nodejs server in https mode:
  1. Change the code of server.js with the following:
    const https = require('https');
    const fs = require('fs');
    
    const options = {
      key: fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem'),
      cert: fs.readFileSync('/etc/letsencrypt/live/example.com/fullchain.pem')
    };
    
    https.createServer(options, app).listen(PORT, ()=>{
       console.log(`Server running https on port ${PORT}`)
      });

  1. Run the following commands:

    su
    node server

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