How to access my IPFS node instance from my express router - node.js

I can't seem to work out the correct approach for running a IPFS node in my express app (/services/IPFS.js), while also being able to access it within my routes (/routes/uploads.js)
/services/IPFS.js
const IPFS = require("ipfs-core");
module.exports = startNode = async (req, res, next) => {
console.log("Starting IPFS node...");
return await IPFS.create();
};
index.js
const express = require("express");
const bodyParser = require("body-parser");
const apiRouter = require("./routes/api");
const cors = require("cors");
const app = express();
const port = 4000;
const startNode = require("./services/IPFS");
app.use(cors());
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use("/api/v1", apiRouter);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
startNode();
How do I pass my IPFS instance through to /routes/upload.js so I can use ipfs.add(file) in my /upload endpoint?
Any help appreciated.
Thanks

You could define the apiRouter as a factory function and pass the startNode function to it. In your router you can then call it:
// in your index.js
// ...
app.use("/api/v1", apiRouter(startNode));
// ...
// in your apiRouter.js
const express = require('express');
const router = express.Router();
module.exports = (startNodeFn) => {
router.post('/upload', async (req, res) => {
const result = await startNodeFn.call(startNodeFn, req, res);
// handle result and do upload ...
});
// rest of routes
// ...
return router;
}

Related

Dynamic BaseUrl in ExpressJs

I'm trying to set the base URL for an Express app on startup.
I can hardcode the base URL and it works just fine:
app.use("/mybaseurl", routes);
However, if I try to use a variable instead which I can export on startup, it fails:
const baseUrl = "/mybaseurl";
app.use(baseUrl, routes);
The above doesn't work.
What am I missing?
test this code, work for me: http://localhost:3000/test
app.js:
const express = require('express');
const userRouter = require('./user');
const app = express();
app.use(express.json());
const baseUrl = '/test';
app.use(baseUrl, userRouter);
app.listen(3000, ()=> {
console.log('Server is up on port ', 3000)
});
user.js:
const express = require('express');
const router = new express.Router();
router.get('/', async (req, res) => {
res.status(200).send('hello');
});
module.exports = router;

I cannot get /users json

I'm new to express and node js, I recently learned how to write API for express but at the end, I get some sort of problem which not resolved by me after several tries. I could not get a response on localhost:8080/users
src/routes/users.js
const { Router } = require("express");
const router = Router();
const getUsers = (req, res) =>
res.send(Object.values(req.context.models.users));
const getUser = (req, res) =>
res.send(req.context.models.users[req.params.userId]);
router.get("/users/", getUsers);
router.get("/users/:userId", getUser);
module.exports = router;
src/routes/index.js
const user = require("./user");
const message = require("./message");
module.exports = {
user,
message
};
src/index.js
const express = require("express");
const app = express();
// Custom Modules
const routes = require("./routes");
const models = require("./models");
// Application-Level Middleware Starts
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
req.context = {
models,
me: models.users[1]
};
console.log(req.context.models.users);
next();
});
// Used Routes
app.use("/users", routes.user);
app.use("/messages", routes.message);
// App Listning to HTTPS Module
app.listen(process.env.PORT);
You need to fix your endpoints in users.js:
router.get("/", getUsers);
router.get("/:userId", getUser);
The reason is because of app.use("/users", routes.user); in your index.js, where the endpoint for users is set. If you leave /users/ in users.js it would be localhost:8080/users/users/. Same problem might be with /messages.

How to make middle ware in Nodejs with express

I'm making express router.
There is some codes like below.
But when I run node this file, it doesn't work.
I think this part make some problem.
This works in Koa but not express.
Could you give me some advice?
const printInfo = (req) => {
req.body = {
method: req.method,
path: req.path,
params: req.params,
};
};
This is the codes in a row.
const express = require('express');
const posts = express.Router();
const printInfo = (req) => {
req.body = {
method: req.method,
path: req.path,
params: req.params,
};
};
posts.get('/', printInfo);
module.exports = posts;
and
const express = require('express');
const api = express.Router();
const posts = require('./posts');
api.use('/posts', posts);
module.exports = api;
and
const express = require('express');
const app = express();
const api = require('./api/index');
app.use('/api', api);
app.listen(4000, () => {
console.log('Example app listening on port 4000!');
});
Your middleware miss the next() call and the router is not configured properly.
Follow this example, is how I always used middleware with Expressjs
middleware.js
// no need to import express/router
module.exports = (req, res, next) => {
// manipulate your body obj
req.body = {
method: req.method,
path: req.path,
params: req.params,
};
// go to the next function
next();
}
routes.js
// only import the router
const router = require('express').Router();
// function for /api/posts
router.route('/posts').post( (req, res) => {
// req.body has been manipulated from the middleware
// do anything you like and call res
res.send("...")
});
// other routes
module.exports = router;
server.js
const express = require('express');
const middleware = require('./middleware');
const routes = require('./routes');
const app = express();
// all calls to /api/* execute the middleware first
app.use('/api', middleware);
// execute the other routes functions
app.use('/api', routes);
app.listen(4000, () => {
console.log('Example app listening on port 4000!');
});

Cannot configure Router in Express NodeJS

I have the next server file:
'use strict'
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const index = require('./routes/index');
const chat = require('./routes/chat');
app.use('/', index);
app.use('/chat', chat);
const port = process.env.API_PORT || 8989;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
and the next two routes index.js and chat.js in ./routes dir:
// ./routes/index.js
const express = require('express');
const router = express.Router();
router.route('/')
.get((req, res) => {
res.json('Hello on the Homepage!');
});
module.exports = router;
// ./routes/chat.js
const express = require('express');
const router = express.Router();
router.route('/chat')
.get((req, res) => {
res.json('Hello on the Chatpage!');
});
module.exports = router;
The first one index.js loads normaly by standart port localhost:8989/, but when I what to get the second route by localhost:8989/chat - I always receive error - Cannot GET /chat...
What is I'm doing wrong?
In server.js
const index = require('./routes/index');
const chat = require('./routes/chat');
app.use('/chat', chat); // when path is :/chat/bla/foo
app.use('/', index);
In ./routes/index.js
router.route('/')
.get((req, res) => {
res.json('Hello on the Homepage!');
});
In ./routes/chat.js
// It is already in `:/chat`. There we need to map rest part of URL.
router.route('/')
.get((req, res) => {
res.json('Hello on the Chatpage!');
});
// ./routes/chat.js
const express = require('express');
const router = express.Router();
router.route('/')
.get((req, res) => {
res.json('Hello on the Chatpage!');
});
module.exports = router;
you can use this

NodeJS Express - How to retrieve list of socketio rooms from controller

I have a socket.io server in my app.js file
const port = process.env.PORT || 3000;
const server = https.createServer(options, app);
const io = require('socket.io');
const ios = io(server);
const routes = require('./routes/index');
app.use('/', routes);
from that file, I know how to get the list of rooms
ios.sockets.adapter.rooms
Now I need to access ios from one of my routes file (in which I also implement "controller" logic, I will refactor later)
# routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
//
// I'd like to check ios.sockets.adapter.rooms HERE
// HOW DO I DO THAT?
});
module.exports = router;
This is one way, maybe no the best way to do it.
You need to pass io instance to your router. I use a wrapper function.
//router.js
const router = express.Router();
const wrapper = function(io){
//work with your router
router.get('/endpoint',(req,res) => {
});
});
export default wrapper;
------------------------------------
//server.js
import yourRouter from "./yourRouter";
//socket
const server = http.createServer(app);
const io = socket(server);
//express
app.use(logger('dev'));
app.use(bodyParser.json());
//here you can pass the instance
app.use(yourRouter(io));
Another way using middleware
//server.js
// middleware
app.use((req, res, next) => {
req.io = io;
next();
});
app.use(yourRouter);
//router.js
import express from 'express';
const router = express.Router();
router.get('/payments/cancel', (req, res) => {
//get the instance
const io = req.io;
res.send('Ok');
});
export default router;
The second one is cleaner, and don't need a wrapper function.

Resources