How to call express api in another api - javascript

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...");
});

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.

Related

using a subdomain as api in nodejs

I want to send a request to api as a subdomain like so :
https://api.example.com
So I have this in server js:
const express = require('express');
const app = express();
const subdomain = require('express-subdomain');
app.use(subdomain('api', require('./_helpers/api')));
In the api.js inside _helper folder I have this:
const express = require('express');
const router = express.Router();
router.post('/', fetch);
module.exports = router;
async function fetch(req, res) {
console.log('fetch api worked');
}
But the console.log('fetch api worked'); never reaches and never execute.
I want to execute the fetch function inside _helper/api.js . How can I do this?

Curl is allowing POST requests but browser is not

I am trying to develop an API that allow POST request of file data, but the POST request only functions using curl curl -X POST --data file= mouse.fa "http://localhost:3000/api/data?file=mouse.fa" . When I trying a POST request in the browser, I get a GET error Cannot GET /api/data. Please could you advise me on how to get the POST request to work in the browser in addition to curl.
router.js
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
fileParser = require("./fileParser")
router.use('./fileParser', fileParser.parse);
// middleware
router.use(function (req, res, next) {
console.log('Received request');
next();
});
router.post('/data', function (req, res) {
//Check file is valid
if (!req.body.file.toString().endsWith('.fa')) {
res.status(400).json({ message: "Bad Request" });
} else {
fileParser.parse(`./${req.body.file.toString()}`);
res.json({ message: "File parsed and data submitted.", location: "/data/" });
}
});
server.js
const express = require('express');
// create server
const app = express();
const port = 3000;
app.listen(port, function () {
console.log(`Server running at ${port}`)
});
// import router
const router = require('./router');
app.use('/api', router)

emitting data using SocketIO in a node app across routes/pages

A form in the index.html will make a post request to the /history route and fetch the data from the MongoDB database:
server.js:
const express = require('express');
const app = express();
const path = require('path');
const http = require('http');
const https = require('https');
const server = http.createServer(app);
const io = require('socket.io')(server);
app.get('/history', (req, res) => {
res.sendFile(__dirname + '/client/history.html');
});
app.post("/history", (req, res)=> {
// fetch data from database
io.emit('data-history', data)
}
In the history.js:
const socket = io('http://localhost:3000');
io.on('data-history', (data) => {
// render data to the page
}
Somehow the data cannot be transferred from server.js to history.js. I am aware that the socket got disconnected when I am switching pages,

close server from within router

I create an express app like this
const express = require('express')
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.post('/close', async (_, res) => {
res.status(200);
res.end();
app.close();
});
module.exports = app;
I instantiate it in another module
const myApp = require('./app.js');
myApp.listen(port, () => {
console.log(`Started server on ${port}`);
});
I want the server to shut itself down when it receives a post request to /close. At the moment, I just get a app.close is not a function error.
I know I can close a server externally like this
const server = myApp.listen(port, () => {
console.log(`Started server on ${port}`);
});
server.close();
but I want to close the server on a post request to /close, how can I do that?
To get access to your server object, try using
req.connection.server
from within your route handler.
.close() makes the server stop listening for new connections. Already-established connections are not affected. The server object emits a 'close' event when all open connections have disconnected.
process.exit() stops your whole nodejs app.
So, this code might do what you want.
app.post('/close', (req, res, next) => {
res.status(200)
res.end()
const server = req.connection.server
if (server.listening) {
server.addEventListener('close', ev => {
console.log('server closed. See ya later alligator.')
process.exit(0)
})
console.log('closing server')
server.close()
}
});
If you need to get the server object from your app object (if getting it from your req object isn't good enough), you could put in a little middleware function like this.
app.use( function adornApp( req, res, next ) {
req.app.locals.server = req.connection.server
next()
} )
Then you'll be able to get your server from app.locals.server once your middleware is first invoked.
You could use the http-terminator package to close your server. The following should do the trick. The reason we use the http-terminator is because the server won't close if it is visited via a route.
const { createHttpTerminator } = require("http-terminator");
const { initApp, app } = require("./app.js");
const PORT = 3000;
const server = app.listen(PORT, () => {
console.log(`Started server on ${PORT}`);
});
const httpTerminator = createHttpTerminator({ server });
initApp(httpTerminator);
Inside the module:
const express = require("express");
const app = express();
const initApp = (httpTerminator) => {
app.get("/close", async (_, res) => {
res.json({ message: "we closed" });
await httpTerminator.terminate();
});
};
module.exports = { initApp, app };

Express Post Request 404

I'll try to make this as to the point as possible. I am trying to make a post request to my express backend. All of the post requests here work, except for "/addpayment". Here is my file called 'router.js'
module.exports = function(app) {
app.post('/signin', requireSignin, Authentication.signin)
app.post('/signup', Authentication.signup)
app.post('/addpayment', function(req, res, next) {
res.send({ message: 'why................' })
})
}
Here is my main 'server.js' file
const express = require('express')
const http = require('http')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const app = express()
const router = require('./router')
const mongoose = require('mongoose')
const cors = require('cors')
// DB Connect
mongoose.connect('mongodb://localhost/demo-app')
// App
app.use(morgan('combined'))
app.use(cors())
app.use(bodyParser.json({ type: '*/*' }))
router(app)
// Server
const port = process.env.PORT || 3090
const server = http.createServer(app)
server.listen(port)
console.log('Server has been started, and is listening on port: ' + port)
I get a 404 in postman, and inside my app browser console. I am using passport in my other routes. I already tried running it through passport when I have a JWT token, and same thing(a 404).
I have already looked at all Stack Overflow/Github posts on the first few pages of google results, with no solution for my use case.
I have made a simplified version of your server and everything works as expected. Only difference that I have made is that I am not creating http server like you, but just calling app.listen
here is working example
router.js
module.exports = function(app) {
app.post('/addpayment', function(req, res, next) {
res.send({message: 'why................'})
})
};
server.js
var express = require('express');
var router = require('./router');
var app = express();
router(app);
//init server
app.listen(3000, function() {
console.log("Server running on port 3000");
});

Categories

Resources