express router use meld to log request parameters and response - node.js

I use meld in my express project and I wanna log my api request with meld,This code below is my first try:
var meld = require('meld');
var express = require('express');
var router = express.Router();
var app = express();
var logger = {
apiAround:function(method){
//TODO:log before request
var result = method.proceed();
//TODO:log after request
return result;
}
};
meld.around(router,'get',logger.apiAround);
router.get('/',function(req,res){
//TODO:handle request
});
app.use('/',router);
but it seems not work,what is the problem?

I found the solution to this problem,actually I want to record my request param/response/response time,so this is code with middleware response-time
var responseTime = require('response-time');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(responseTime(function(req,res,time){
if(req.baseUrl.indexOf('/xxxxxx') !== -1)
{
console.log(req.body);
console.log(time);
console.log(res);
}
}));

Related

Both POST/GET requests yield a 404 error in Postman. Is my Express routing to blame?

I am intending to set up a Node.js server with MongoDB to handle HTTP CRUD requests. Upon setting up my endpoint I was initially able to receive POST/GET requests, however the handling of the document objects became the issue. Upon trying to fix this issue I am now unable to POST/GET at all? Is this simply a syntax issue or is my code doomed?
const MongoClient = require('mongodb').MongoClient;
var QRCode = require('qrcode');
var canvasu = require('canvas');
var express = require('express');
var mongoose = require('mongoose')
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var db;
var collection
var Patient = require('./ShiftAssist/models/patientModel');
var router = express.Router();
''
CODE FOR CONNECTION
''
router.get('/patients/:Pnum', function(req,res,next){
Patient.findOne({Pnum:req.params.Pnum},function(err,patient){
if (err) return next(err);
res.json(patient);
})
});
app.use('/', router);
app.listen(3000, function () {
console.log('Example app listening on port ' + port + '!');
});
Expected: GET request to http://127.0.0.1:3000/patients/XXXXXX with a document identifier, returns entire document
Actual: Timeout Error
try to change you route by /patients/:Pnum
and your request should be http://127.0.0.1:3000/patients/XXXXXX
source: https://expressjs.com/en/guide/routing.html
EDIT: Code i used so far
var express = require('express');
var app = express();
var router = express.Router();
router.get('/patients/:Pnum', function (req, res, next) {
setTimeout(() => res.json({ ok: req.params.Pnum }), 1000)
});
app.use('/', router);
app.listen(3000);

Node express cannot get static file

This is the picture of my server
https://drive.google.com/file/d/1GA57RyYsc5ik1pSlLhAGtgGjbp_vLFoH/view?usp=sharing
When I go to http://localhost:3000/
I get the error message: Cannot Get/
myserver.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Whenever you are trying to visit any url on the browser , then browser makes a GET request to that url, in your case you are not sending any response on the url: "http://localhost:3000/. You can try something like this.
app.route('/*')
.get(function(req, res) {
res.sendFile(path.resolve("./client") + '/index.html'));
});
Check the naming you used, it shows myserver.js instead of server.js as in the picture you uploaded.
Check your routing on line 10 of you code
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
. try this edited codes
server.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./server/lions');
var tigerRouter = require('./server/tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Express static directory is given client but it is present on parent directory.
So i have resolve this issue with path module and now this will work for you.
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var path = require('path')
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static(path.join(__dirname, '../client')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Your code works fine after commenting the following three lines of your code:
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use('/lions', lionRouter);
Check if any error is present in LionsJS.

Nodejs return data after get request inside a post request

i'm trying to pass get request answer to the post request but can't, can someone help me please?
var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var request = require('request');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
http.listen(9999, function() {
console.log('listening...');
});
app.post('/bot',function(req,res){
var apiurl = 'https://apiURI'
request(apiurl, function(error,response,body){
res.send(body)
})
}
when i receive the api answer should send to client who make the post request with res.send
error: Can't set headers after they are sent.
Error solved, deleting the end() method outside the get request due to it's a async request (my mistake)
var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
var request = require('request');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
http.listen(9999, function() {
console.log('listening...');
});
app.post('/bot',function(req,res){
var apiurl = 'https://newsapi.org/v1/articles?source=techcrunch&apiKey=72cc6a313e2b4fb3af09e4593ee06fbc'
request(apiurl, function(error,response,body){
res.send(body)
})
//res.end()
})

Error in implementing router

Here is my code.
server.js
var express = require('express'),
bodyParser = require('body-parser'),
log = require('./libs/log')(module),
api = require('./libs/api.js'),
app = express();
// settings
app.set('port', 5000);
// to process post requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// routes
rawQuestionRouter = require('./routes/rawQuestionRoutes.js');
app.use('/rawQuestions', rawQuestionRouter);
and routes/rawQuestionRoute.js:
var express = require('express');
var routes = function() {
var rawQuestionRouter = express.Router();
rawQuestionRouter.route('/test')
.post(function(request, response) {
log.debug(request.body);
response.send('raw question saved');
});
return rawQuestionRouter;
}
module.exports = routes;
Update:
When I make a POST request on '/rawQuestions/test' the server don't respond. Why?
You're exporting the routes function, which is not a router (it returns one, but that's not the same).
There are several solutions:
// server.js
app.use('/rawQuestions', rawQuestionRouter());
Or:
// routes/rawQuestionRoute.js
module.exports = routes();
Or just remove the entire routes function altogether and export the router instance directly.

ExpressJS cannot get POST

The relevant part of my app.js is as follows
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var routes = require('./config/routes);
app.use('/', routes);
My route file is:
var express = require('express');
var router = express.Router();
var upgradesController = require('../../app/controllers/upgrades.server.controller');
// This should receive POST requests
router.post('/api/upgrades/device', upgradesController.create);
module.exports = router;
And finally my controller is
exports.create = function(req, res) {
res.send(req.body);
}
But this sends nothing. It's always an empty JSON value. I'm using PostMan for testing:
What is happening?
You're sending form-data, switch to x-www-form-urlencoded instead. You can also send "raw", and input valid JSON.

Resources