Logger is not a function error in Node.js - javascript

As in my previous questions I said, I am trying to create an HTTP server, testing some middlewares codes, but in my code right now is giving basically the same error from another times, but I can't see where I am getting this wrong.
My code :
logger.js
var http = require('http');
var connect = require('connect');
var app = connect();
// setup logger middleware
app.use(connect.logger());
// actually respond
app.use(function(req, res) {
res.end('Hello World!');
});
http.createServer(app).listen(8080);
He points out to the connect.logger() even if I am using app.use(), still gives me this error.
connect.logger is not a function

Connect no longer comes with a built-in logger! Try using some logging library like morgan
var http = require('http');
var connect = require('connect');
var logger = require('morgan');
var app = connect();
// setup logger middleware
app.use(logger("combined")); //Without one string in logger() it will give deprecated morgan format, so it needs to use some string for work, the documentation it say so.
// actually respond
app.use(function(req, res) {
res.end('Hello World!');
});
http.createServer(app).listen(8080)

Related

massive.connectSync not a function

Why do I get this error, massive.connectSync is not a function when I run server.js. It works on my mac, but not my windows. Please help solve this enter code hereerror
var express = require("express");
var app = express();
var http = require('http');
var massive = require("massive");
var connectionString = "postgres://massive:#localhost/MarketSpace";
// connect to Massive and get the db instance. You can safely use the
// convenience sync method here because its on app load
// you can also use loadSync - it's an alias
var massiveInstance = massive.connectSync({connectionString : connectionString})
// Set a reference to the massive instance on Express' app:
app.set('db', massiveInstance);
http.createServer(app).listen(8080);
Synchronous functions are no longer supported, and the connect function itself no longer exists, it's all promises all the way:
var express = require("express");
var app = express();
var http = require('http');
var massive = require("massive");
var connectionString = "postgres://massive:#localhost/MarketSpace";
massive(connectionString).then(massiveInstance => {
app.set('db', massiveInstance);
http.createServer(app).listen(8080);
});
Note that massive requires node > 6. If you are using and older version you'll need to update node in order to use massive.
Docs

How to set a variable to the result of morgan (not to log it on the console) in Node.js

I do not understand the stream in node well.
I try to save my app's request and response information to the mongodb.
Firstly, I want to set a variable to the result of morgan:
var apiInfo = morgan('dev')
app.use(console.log('test______',apiInfo))
However, it does not work. I know this in the morgan official site:
var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')
var app = express()
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'})
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))
app.get('/', function (req, res) {
res.send('hello, world!')
})
But I do not want to save the result to the access.log, and I just want to save the result to a variable apiInfo.
use the project https://www.npmjs.com/package/mongo-morgan. Use regular expressions to modify the stream in the index.js , and then you can easily put Morgan's data to Mongodb

Passing req.body through Express middleware to routes

I'm using the body-parser npm package to parse POST data in Application/JSON format and using a few different express routers to modularize the routes I'm creating. Here's the important info in my main server.js file:
server.js
var express = require('express');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
// I'm using a sessionId to identify a person in this dummy app instead of adding in authentication. So the API call is sent to http://localhost:5000/johndoe/todo
app.use('/:sessionId/todo', require('./routes/todoRoutes'));
var port = process.env.PORT || 9191;
app.listen(port, function () {
console.log('Express server listening on port ' + port);
});
todoRoutes.js:
var todoRouter = require('express').Router();
todoRouter.post('/', function (req, res) {
console.log("This is the post data:");
console.log(req.body);
});
module.exports = todoRouter;
req.body seems to be getting lost through the middleware; it logs {} to the console. However, on a whim I added the following to my bodyParsing middleware in server.js:
app.use(bodyParser.json(), function (req, res, next) {
next();
});
And now it's passing req.body through to todoRoutes.js. (It now logs {title: 'Testing'}, etc. to the console like I need it to.)
What's going on here? And what's the best way to structure this so that it works the way it's supposed to? I'm new to Express, so I admit I could be structuring this all wrong.
Ugh, nevermind. I was an idiot and found that the Content-Type Header of application/JSON got turned off in Postman (read: I must have turned it off at some point) and so the bodyParser was never being used.
Dammit.
Thanks for the help to those who responded!

request.url Express and Node

Im a newbie on node.js, I just wanted to know how to extract the requested url in this code
app.use(express.static(__dirname+"/public"));
Thank you for your help
As you can see on the static middleware source, a middleware is basic a function that receives the parameters (request, response, next_function).
So you could create a function that reads the url before it goes to static middleware.
var express = require('express');
var app = express();
var staticfn = express.static(__dirname+'/public');
app.use(function (req,res,next) {
console.log(req.url);
var sendStream = staticfn(req,res,next);
console.log(sendStream.path);
});
app.listen(3000)
As you can see on the send package used by the static middleware, the send function returns a object called SendStream.

Understanding vhost in Express Node.js

I am trying to understand how vhost actually works in Express JS. Here's a working code sample (forgot where I pulled this from):
// -- inside index.js --
var EXPRESS = require('express');
var app = EXPRESS.createServer();
app.use(EXPRESS.vhost('dev.example.com', require('./dev').app));
app.listen(8080);
// -- inside dev.js --
var EXPRESS = require('express');
var app = exports.app = EXPRESS.createServer();
app.get('/', function(req, res)
{
// Handle request...
});
Now, my question is, why do we call createServer() twice? Why does this even work? Is vhost internally "merging" the two servers together?
Node.js is event-driven, and when a request comes in, the request event is raised on a http.Server. So basically, express.vhost (or really, connect.vhost) is a middleware function which raises the request event on another instance of a http.Server:
function vhost(req, res, next){
if (!req.headers.host) return next();
var host = req.headers.host.split(':')[0];
if (req.subdomains = regexp.exec(host)) {
req.subdomains = req.subdomains[0].split('.').slice(0, -1);
server.emit('request', req, res);
} else {
next();
}
};

Categories