why i am getting undifine when i console req.query? - node.js

this is api.js file
function apiKey(res, req, next) {
const api_key = '12345678';
console.log(req.query);
next();
}
module.exports = apiKey;

You named it wrong way. should be like this
function apiKey(req, res, next) {
const api_key = '12345678';
console.log(req.query);
next();
}
module.exports = apiKey;

Related

Express static with Middleware require login

I created two uploads folder are public and private. Public folder does not require auth but private folder will require a middleware to access;
app.use('/uploads', express.static('uploads/public/'));
app.use('/uploads', require('./admin/routers/api/accessPrivate'), express.static('uploads/private/'));
And here is my accessPrivate
const userPermission = require("../../middleware/permission");
const auth = require('../../middleware/auth');
const accessMedia = async ( req, res, next) => {
await auth(req, res, next);
next();
};
module.exports = accessMedia;
But it shows error: "No token". It means that there is no req header sent to server; Can you tell me how to do?
Thank you so much;
Define a general middleware for all uploads requests. Check the user's permission.
app.use('/uploads', async (req, res, next) => {
let hasAccess = await auth(req, res, next);
if (hasAccess) {
app.use(express.static('uploads/private/'));
}
else {
app.use(express.static('uploads/public/'));
}
next();
});
// your routes
app.use('*', function (req, res, next) {
let target = 'index.html';
if (req.baseUrl && req.baseUrl != '/') {
target = req.baseUrl;
}
if(req.user) {
root = 'uploads/private/';
}
else {
root = 'uploads/public/';
}
res.sendFile(target, { root: root })
});
Also you should change the auth implementation.

expressjs write multiple middleware and import it to the main file

I have a script which holds a middleware like:
module.exports = function (req, res, next) {
req.requestTime = Date.now()
next()
}
In a file I can import this but how can I write multiple middleware and export all of them and import it?
I am learning express and got stuck here :)
write multiple middlewares in one file and exprot them all.
function middleware1(req, res, next) { req.requestTime = Date.now(); next() }
function middleware2(req, res, next) { req.requestTime = Date.now(); next() }
function middleware3(req, res, next) { req.requestTime = Date.now(); next() }
module.exports = {
middleware1 : middleware1,
middleware2 : middleware2,
middleware3 : middleware3
}
then if you want to import them you can either import all of middlewares like
var middleware = require("./middlewares")
// name of middleware file in require
then use them like
app.get('/profile', middleware.middleware1, function (req, res) {
// do your stuff
});
Or you can import a single middleware by adding middleware function name in require
var middleware1 = require("./middlewares").middleware1
then use them like
app.get('/profile', middleware1, function (req, res) {
// do your stuff
});
I was trying to do the same, but my scenario was a bit different
I had type module in package.json
{
"type": "module"
}
middleware file and exporting
const authenticate_middleware = (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const items = authHeader.split(' ');
/*check count 2*/
/*check 1st item is barner*/
/*check and validate 2nd item*/
const token = items[1];
let user = {
id: 1,
token: token
}
req.user = user;
next();
} else {
res.sendStatus(401);
}
};
const developer_middleware = (req, res, next) => {
const authHeader = req.headers.developer; /*all lower case apiKey was undefined*/
if (authHeader) {
let developer = {
id: 1,
apiKey: authHeader
}
req.developer = developer;
next();
} else {
res.sendStatus(401);
}
};
export default authenticate_middleware;
export let authenticate = authenticate_middleware;
export let developer = developer_middleware;
importing modulewares
//import multiple
import { authenticate, developer } from '../middlewares/all.js'
//import single
import { developer } from '../middlewares/all.js'
// import default
import authenticate from '../middlewares/all.js'

Display middleware value in Jade Template

I have the following sample middleware component that I want to display in the index.jade file. Is this possible? How do you add the req.requestTime in the Jade template?
var requestTime = function (req, res, next) {
req.requestTime = Date.now();
next();
};
app.use(requestTime);
Add a property to res.locals and you can use it in Pug (formerly Jade)
var requestTime = function (req, res, next) {
req.requestTime = Date.now();
res.locals.requestTime = req.requestTime;
next();
};
var requestTime = function (req, res, next) {
req.requestTime = Date.now();
res.locals.requestTime = req.requestTime;
next();
};
//Jade renderer
var jadeRenderer = function(req, res) {
var jadeFile = 'path/to/jade/template';
var jadeVars = {
locals: req.locals,
queryParams: req.query //if you desire?
};
res.render(jadeFile, jadeVars, function(err, html) {
if(err) {
//handle error
}
res.send(html);
});
};
//jade template
<p>#{locals.requestTime}</p>

Seperate api and web in route

Trying to separate api and web route:
route/index.js
var api = function () {
router.get('/:id', function (req, res, next) {
...
});
return router;
}
var web = function () {
router.get('/:id', function (req, res, next) {
...
});
return router;
}
module.exports = {
api: api,
web: web
};
app.js
var indexAPI = require('./app/routes/accounts').api;
var indexWeb = require('./app/routes/accounts').web;
app.use('/api/index', indexAPI);
but it didn't route successfully.
I have change it to and it is working:
var api = (function () {
router.get('/:id', function (req, res, next) {
...
});
return router;
})();
var web = (function () {
router.get('/:id', function (req, res, next) {
...
});
return router;
})();
module.exports = {
api: api,
web: web
};

Param parsing twice for nested routes in Express

When I make GET http://localhost:8080/messages/3/sentiments for the code below why param method is called two times? So If I have 10 routes it will be called 10 times?
var comments = new Router();
comments.get('/comments', function (req, res, next) {
res.send('Comments by message_id=' + req.message._id);
})
var sentiments = new Router();
sentiments.get('/sentiments', function (req, res, next) {
res.send('Comments by message_id=' + req.message._id);
})
var messages = new Router();
messages.param('_message', function (req, res, next, _id) {
console.log("Set message");
fs.readFile(__filename, function () {
req.message = { _id: _id };
next();
});
})
messages.use('/messages/:_message/', comments);
messages.use('/messages/:_message/', sentiments);
app.use(messages);
app.listen(8080);
Confirmed to be a bug in Express < 4.3
https://github.com/visionmedia/express/issues/2121

Resources