0

I have an express server in a file server1.js and I have another server in a file server2.js. I would like to know how I can call Server2 getUserId api in the Server1 addUser api?

server1.js

// Server1
const express = require("express");
const app = express();

app.get('/api/addUser/:userName', (req, res) => {
    const user = {
      userName: req.params.userName,
      userId: // call to getUserId api to get userId from server2
    };
    users.push(user);  
    res.json(`user addedd: ${JSON.stringify(user)}`);
    });

app.listen(3000, () => {
    console.log("Listen on the port 3000...");
}); 

Server2.js

// Server2
const express = require("express");
const app = express();

app.get('/api/getUserId', (req, res) => {
    res.json(Math.random());
    });

app.listen(3001, () => {
    console.log("Listen on the port 3001...");
});
bunny
  • 1,797
  • 8
  • 29
  • 58
  • If all that getUserId does is call Math.random(), I would recommend just adding that line to addUser rather than adding the complexity of an API call. – ddastrodd Jan 03 '23 at 18:20
  • 1
    I'm not sure I understand the setup and the problem. You are running it as one service under port 3000? If so, I recommend extracting the method and calling it as a function where it needs to be used – 697 Jan 03 '23 at 18:22
  • This is just an example and the main point is I would like to know how to call api from another server. I simplified my problem and make the example simple. Server2 is running in a different port so not typo. – bunny Jan 03 '23 at 18:46
  • 1
    Then please correct it in your example. There you have port 3000 as listening port on both examples but Server2 prints 3001 to the console. - And have you tried [sending http request in node](https://stackoverflow.com/questions/9639978/sending-http-request-in-node-js)? – Christopher Jan 03 '23 at 19:08
  • Got it, thank you! Let me give it a try. – bunny Jan 03 '23 at 19:27

1 Answers1

0

It looks like you just use HTTP(s) to call the other API. Node has built in HTTP and HTTPS modules or you can use a 3rd party library to do HTTP GET.

Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91