using a subdomain as api in nodejs - javascript

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?

Related

How to call express api in another api

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.

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)

get all registered route in nodejs [duplicate]

This question already has answers here:
How to get all registered routes in Express?
(31 answers)
Closed 2 years ago.
i want to return all registered route in my project.
i use this code for retur nall routes :
const app = require("express");
let routers = app._router.stack
.filter((r) => r.route)
.map((r) => {
return {
method: Object.keys(r.route.methods)[0].toUpperCase(),
path: r.route.path,
};
});
but it not worked and show me this error :
(node:13092) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'stack' of undefined
Edit :
my routes :
const express=require('express');
const router=express.Router();
const roleRouter=require('./role');
const userRouter=require('./user');
const managerRouter=require('./manager');
const accessRouter=require('./access');
const settingRouter=require('./setting');
router.use('/role',roleRouter);
router.use('/user',userRouter);
router.use('/manager',managerRouter);
router.use('/access',accessRouter);
router.use('/setting',settingRouter);
module.exports=router;
and use that in the main js file :
app.use(require("./routes/index"));
how can i return all routes in my projects ???
the app supposed to be created with express function
const express = require('express');
const app = express();
then you can get all of the registered routes, make sure to put this line after you register your app routes
console.log(app._router);
So the full code will look like this:
const express = require('express');
const app = express();
const port = 3000;
console.log(app._router); // undefined
app.get('/', (req, res) => res.send('Hello World!'))
console.log(app._router.stack); // showing routes
app.listen(port)
EDIT:
To return all of your routes from your API endpoint, you can do this (not sure why you want to do this though)
const express = require('express');
const app = express();
const port = 5000;
app.get('/', (req, res) => {
res.json(app._router.stack);
})
app.get('/example', (req, res) => {
// This route will also be listed when you call "/"
res.send();
})
app.listen(port)

How to call a socket.on() from a separated file

I'm trying to call a socket.on() event from an external .js file and I can't figure out what I'm missing...
I'm using NodeJS with ExpressJS.Below are the files:
app.js(the server file)
const fs = require('fs');
const express = require('express');
const app = express();
const http = require('http').Server(app);
var io = require('socket.io')(http);
....
//Socket Io functions
const ioObj = require( './library/io.js')(app, express, io);
// This route will be used to print the type of HTTP request the particular Route is referring to
router.use(function (req, res, next) {
console.log("/" + req.method);
next();
});
....
/library/io.js (sockets file)
module.exports = function(app, express, io){
io.on('connection', async function(socket) {
socket.on('refreshPage', function(){
console.log("page should now be refreshed !!");
socket.emit("refreshPageNow");
});
....
});
}
What I'm trying to do is to call/access the refreshPage event from /library/io.js so I can send further a "refresh webpage" signal.
I tried to do something like :
io.sockets.emit("refreshPage");
and
ioObj.sockets.emit("refreshPage");
But didn't work...

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