Express router and routes Node.js - node.js

I get this error when I try to route my
My code
'use strict';
const express = require('express');
const app = express ();
const chatCat = require ('./app');
app.set('port', process.env.PORT || 3000);
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use('/', chatCat.router);
app.listen(app.get('port'), () => {
console.log('running on port:', app.get('port'));
});
Error
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
I tried routing but it keeps giving me errors from my express.js.

Try this code:
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.static('public'));
app.set('view engine', 'ejs');
var chatCat = require('./app');
app.use('/',chatCat);
app.listen(port,function(){
console.log("Server is running on port: "+port);
});

Try creating app with this https://expressjs.com/en/starter/generator.html it will create nice structure for your project. As for your error - it needs to be express middleware function. You can't import router from your app.js as it don`t have such property. If you want to have route described here use:
app.method('/yourRoute', function(req, res, next){
//your middleware code
});
also change this:
app.listen(app.get('port'), () => {
console.log('running on port:', app.get('port'));
});
to this:
app.listen(3000);
And you can change 3000 to any unused port you want

Related

exphbs is not a function

I have been trying to test out express and express handlebars. I have read and tried a few demos. They all basically the same but I cannot get any of them to work. The error I keep getting is -
app.engine('handlebars', exphbs());
^
TypeError: exphbs is not a function
here is my code below:
const express = require("express");
const exphbs = require("express-handlebars");
const app = express();
const port = 8000;
//Handelbars Middleware
app.engine("handlebars", exphbs());
app.set("view engine", "handlebars");
// Index Route
app.get("/", function (req, res) {
res.render("home");
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
I made a short video to further explain - https://www.awesomescreenshot.com/video/6352907?key=df18cdbdf4ed12b85d2c92458ad9a2de
I thought const exphbs = require('express-handlebars'); was declared a function
Thanks
exphbs is not function u can try this code..
const express = require('express');
const exphbs = require('express-handlebars');
// const { engine } = require('express-handlebars');
const app = express();
const port = 8000;
//Handelbars Middleware
//app.engine('handlebars', engine());
app.engine('handlebars', exphbs.engine());
app.set('view engine', 'handlebars');
// Index Route
app.get('/', function (req, res) {
res.render('home');
});
app.listen(port, () =>{
console.log(`Server started on port ${port}`);
});
I think You should use example as reference from express-handlebars. To use this code you need add to your pacakge.json file this line "type": "module",(ES6 import) Good Luck!
import express from 'express';
import { engine } from 'express-handlebars';
const app = express();
app.engine('handlebars', engine());
app.set('view engine', 'handlebars');
app.set('views', './views');
app.get('/', (req, res) => {
res.render('home');
});
app.listen(8000);

routing node.js and express

I'm having a problem routing in express 4. I was following the example, but it isn't loading. I'm just getting a spinning wheel.
How do you do routing in express version 4?
app.js:
var express = require('express');
var http = require('http');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
var port = (process.env.PORT || process.env.VCAP_APP_PORT || 5000);
app.use('/birds', require('./controller/bird'));
http.createServer(function (req, res) {
//res.writeHead(200, {'Content-Type': 'text/plain'});
//res.end('Hello World!\n');
}).listen(port);
console.log('Server running at http://127.0.0.1:'+port);
bird.js:
var express = require('express');
var router = express.Router();
// middleware specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
You're not calling the app.listen() function. Instead of the http.createServer one, you should invoke the Express function.
Please, take a look at a basic example.
Relevant code:
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Edit: as slebetman wrote in the comment, the more general way for it is:
http.createServer(app).listen(port, function(){
console.log('now listening on port ' + port);
});

Including API routes in Express 4.x

I'm learning MEAN stack with 'Getting MEAN with...' book, and problem is older Express version in books than i use.
The first step is to tell our application that we’re adding more routes to look out for,
and when it should use them. We already have a line in app.js to require the server
application routes, which we can simply duplicate and set the path to the API routes
as follows:
var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');
Next we need to tell the application when to use the routes. We currently have the following line in app.js telling the application to check the server application routes for
all incoming requests:
app.use('/', routes);
Notice the '/' as the first parameter. This enables us to specify a subset of URL s for
which the routes will apply. For example, we’ll define all of our API routes starting
with /api/ . By adding the line shown in the following code snippet we can tell the application to use the API routes only when the route starts with /api :
app.use('/', routes);
app.use('/api', routesApi);
And there's listing of my app.js file:
var express = require('express')
, others = require('./app_server/routes/others')
, locations = require('./app_server/routes/locations')
, routesApi = require('/app_api/routes/index')
, ;
require('./app_server/models/db')
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/app_server/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
// LOCATION PAGES
app.get('/', locations.homeList);
app.get('/location', locations.locInfo);
app.get('/location/review/new', locations.addReview);
// OTHER PAGES
app.get('/about', others.about);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
Can someone explain me how to do the same in my Express version ?
In Express 4, this is done using Router Middleware. More info is available on Express Routing here.
A Router is simply a mini express app that you can define middleware and routes on that should all be packaged together, ie /api should all use apiRouter. Here is what apiRouter could look like
apiRouter.js
var express = require('express')
var router = express.Router(); // Create our Router Middleware
// GET / route
router.get('/', function(req, res) {
return res.status(200).send('GET /api received!');
});
// export our router middleware
module.exports = router;
Your main Express app would stay the same, so you would add your router using a require() to import the actual file, and then inject the router with use()
Express Server File
var express = require('express');
var app = express();
var apiRouter = require('../apiRouter');
var port = process.env.PORT || 3000;
app.use('/', apiRouter);
app.listen(port, function() {
console.log('listening on ' + port);
});

Why my module.exports doesn't work?

Here is my basic node.js app with only two files:
app.js
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
module.exports = {
test: "test"
};
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// defining middlewares
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
and my index.js:
var server = require('../app');
exports.index = function(req, res){
console.log(server);
res.send('Hello world');
};
My problem is when I go to http:\\localhost:3000 , I see in my console {} instead of {test: "test"} , it looks like the module.eports doesn't work correctly. Why ?
Requiring index.js from within app.js, and then requiring app.js from within index.js, looks like code smell to me. Additionally, if you use var app = module.exports = express() then Express is able to treat your app as middleware (so for instance, you could have a second app that requires the first app, and passes some requests to it.
When I need to access app inside another required file I do the following:
// ./routes/index.js
module.exports = function(app){
var routes = {};
routes.index = function(req, res){
console.log(app.myConfig);
res.send('Hello world');
};
return routes;
};
// ./app.js
var app = module.exports = express();
app.myConfig = {foo:'bar'};
var routes = require('./routes/index.js')(app);
You don't need to include app in index.js
indes.js should just be
exports.index = function(req, res){
console.log(server);
res.send('Hello world');
};
And I am assuming index.js is in the routes folder like so
app.js
routes
index.js

Error while compiling WebStorm Node.js project

I just created a simple project in WebStorm using Express module
then I install mongoose and after that I have tried to connect to MongoDB, but it's giving this exception:
Index.js
var mongoose = require('mongoose');
mongoose.connect('localhost', 'Test');
var schema = mongoose.Schema({ name: 'string' },{age:'int'});
var Human = mongoose.model('Human', schema);
exports.saveHuman = function (req,res){
"use strict";
var Ahs = new Human({name:'Dumy'},{age:24});
Ahs.save(function(error , data ){
if(error){
console.log("Not working");
}
else{
res.send(Ahs.name + "Created !");
}
});
};
exports.index = function(req, res){
"use strict";
res.render('index', { title: 'Express' });
};
app.js
var express, routes, user, http, path;
express = require('express');
routes = require('./routes');
user = require('./routes/user');
http = require('http');
path = require('path');
var app = express();
app.configure(function(){
"use strict";
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
"use strict";
app.use(express.errorHandler());
});
app.get('/saveHuman',routes.saveHuman);
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
"use strict";
console.log("Express server listening on port " + app.get('port'));
});
Now, when I run the project it shows this in console .

Resources