I cannot get /users json - node.js

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.

Related

Getting an undefined token of add category in console

I am new to React and Node and I'm getting an undefined token in console when I add category I get undefined in the console. I am using cookie-parser.
server.js file:
const express = require('express');
const app = express();
const cors = require('cors');
const morgan = require('morgan');
const cookieParser = require('cookie-parser')
const connectDB = require('./database/db');
const authRoutes = require('./routes/auth');
const categoryRoutes = require('./routes/category');
//middleware
app.use(cors());
//dev specifies it is for development
app.use(morgan('dev'));
//express.json allows us to parse incoming request in json in the format of a json
app.use(express.json());
app.use(cookieParser());
app.use('/api/auth', authRoutes);
//route for category
app.use('/api/category', categoryRoutes);
connectDB();
app.get('/', (req,res) => {
res.send('Inside Server');
});
const port = process.env.PORT || 5000;
app.listen(port, ()=>console.log(`Listening on port ${port}`));
category.js (controller file)
exports.create = (req,res) => {
setTimeout(()=> {
res.json({
successMessage: `${req.body.category} was created!`
});
}, 5000);
};
category.js (routes file)
const express = require('express');
const router = express.Router();
const categoryController = require('../controllers/category');
const { authenticateJWT } = require('../middleware/authenticator');
router.post('/', authenticateJWT , categoryController.create);
module.exports = router;
authenticator.js (middleware file)
const jwt = require('jsonwebtoken');
const { jwtSecret } = require('../config/keys');
exports.authenticateJWT = (req, res, next) => {
const token = req.cookies.token;
console.log(token);
}
keys.js file
//it is gonna tell us/ signifying if we are live if in develoopment or in production
const LIVE = false;
if (LIVE) {
module.exports = require('./prod.js');
} else {
module.exports = require('./dev.js');
}
Console screen:
Instead of undefined i should be getting token.
Any help will be highly appreciated.
Thanks!
Is there a token Cookie available? (You can check using the inspector of your browser, normally in the „application“ tab. If you are sending the request using any tools like postman, curl, wget, …, you have to set the cookie first.)
Was the cookie available on any other routes? What’s the difference between these routes and the category route? Is it possible that your cookie is constrained to a specific path, e.g. to /api/auth? If so, adjust the path in res.cookie.

How to access my IPFS node instance from my express router

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;
}

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!');
});

How to app use all routes from different file

I'm trying to separate my routes, previously i'm including them to my app.js
/backend/app.js
const express = require("express");
const router = require("./routes");
const status = require("./routes/status");
const register = require("./routes/register");
const login = require("./routes/login");
app.use('/', router);
app.use('/status', status);
app.use('/login', login);
app.use('/register', register);
I realized its not ideal since i am adding more and more routes later on and the app.js will be polluted with them
What i want to do now is just to import an index.js to app.js and basically this index have all the routes needed
/backend/routes/index
const routes = require("express").Router();
const root = require("./root");
const status = require("./status");
const register = require("./account/register");
const login = require("./account/login");
routes.use("/", root);
routes.use("/login", login);
routes.use("/register", register);
routes.use("/status", status);
and now in the app.js i can just include the index
const routes = require("./routes");
app.use('/', routes);
but its not working im getting 404 error when trying to request to login route
im exporting them like this
module.exports = routes;
In your app.js
app.use('/', require('./backend/routes/index'))
Then, in your routes/index
import express from 'express'
const router = express.Router()
// GET /
router.get('/', function (req, res) {
})
// GET /countries
router.get('/countries', (req, res, next) => {
})
// POST /subscribe
router.post('/subscribe', checkAuth, generalBodyValidation, (req, res, next) => {
})
// All routes to /admin are being solved in the backend/routes/admin/index file
router.use('/admin', require('./backend/routes/admin/index'))
module.exports = router
Your admin/index file can be
import express from 'express'
const router = express.Router()
// POST /admin/login
router.post('/login', (req, res, next) => {
})
module.exports = router
With this, you will be able to perform a POST request to /admin/login.
Hope this solves your problem, if it does mark my answer as correct, if not tell me what went wrong and I will solve it :D

Express Middleware Issue

On routes/index.js it works fine if I leave the module.exports = routes;
But If I change it to the following to allow multiple files then I get a middleware error:
module.exports = {
routes
};
var app = express();
const routes = require('./routes');
const port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use('/', routes);
app.get('/', (req, res) => {
res.send('Please visit: http://domain.com');
}, (err) => {
res.send(err);
});
//routes/index.js
const routes = require('./MainRoutes');
module.exports = routes;
//routes/Main Routes.js
const routes = require('express').Router();
routes.post('/main', (res, req) => {
//code here works
});
module.exports = routes;
The error is: Router.use() requires middleware function but got a ' + gettype(fn));
MainRoutes.js exports the express router object, which middleware will understand just fine if you do
module.exports = routes; // routes/index.js
However, when you do
module.exports = {
routes
};
You are now nesting that router object in another object, which middleware can't understand.
In your main server file you can do
const {routes} = require('./routes');
to get the router object properly.
Modify the routes/index.js as:
const routes = require('express').Router();
routes.use('/main', require('./MainRoutes'));
// Put other route paths here
// eg. routes.use('/other', require('./OtherRoutes'))
module.exports = routes;
Modify the Main Routes.js as:
const routes = require('express').Router();
routes.post('/', (res, req) => {
// route controller code here
});
module.exports = routes;
Hope this helps you.

Resources