koa-router error router.routes is not a function - javascript

When I try to use koa-route 3.2.0 example from their website, I got error message router.routes is not a function
const Koa = require('koa');
const router = require('koa-route');
const app = new Koa();
app.use(logger());
router.get('/users', (ctx, next) => {
ctx.response.body =`<h1>Hello!</h1>`;
});
app.use(router.routes())
.use(router.allowedMethods());
// don't listen to this port if the app is required from a test script
if (!module.parent) {
app.listen(1337);
console.log('listening on port: 1337');
}
I got error message:
app.use(router.routes())
^
TypeError: router.routes is not a function
at Object.<anonymous> (/Projects/shoucast-front-end-prototype/script/server.js:40:16)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3
When I try to change
const router = require('koa-route');
to
var router = require('koa-router')();
I got error message:
const router = require('koa-route')();
^
TypeError: require(...) is not a function
at Object.<anonymous> (/Projects/shoucast-front-end-prototype/script/server.js:2:36)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3

Looks like you've installed the newer version, available at https://github.com/alexmingoia/koa-router/tree/master
You need to use new Router() instead.
Also looks like you're mixing up koa-router with koa-route, which are two different packages.
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
router.get('/', function (ctx, next) {
// ctx.router available
});
app
.use(router.routes())
.use(router.allowedMethods());

Related

Why can't I use middleware in my express route?

I am creating an API, so I want to add a user system and validate access to the API.
This would be the middleware for validation:
'use strict'
const jwt = require('jwt-simple');
const moment = require('moment');
const config = require('../settings/config');
function isAuth(req, res, next) {
if (!req.headers.authotization) {
return res.status(403).send({
message: `No tiene autorizacion`
})
}
const token = req.headers.authotization.split(" ")[1];
const payload = jwt.decode(token, user, config.token.secret_token);
if (payload.exp <= moment().unix()) {
return res.status(401).send({
message: 'El token ha expirado'
})
req.user = payload.sub;
next();
}
}
module.exports = isAuth;
while this would be the route:
'use strict'
const express = require('express');
const router = express.Router();
const auth = require('../middlewares/auth');
router.get('/', auth.isAuth, (req, res) => {
res.status(200).send({
message: `Tienes acceso`
})
})
on the other hand, this is my main application settings (app.js):
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const app = express();
const config = require('./config')
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan('dev'));
// Routes variables
const productRouter = require('../routes/product');
const privateRouter = require('../routes/private');
// Routes uses
app.use('/api/product', productRouter);
app.use('/private', privateRouter);
app.listen(config.app.port, err => {
if (err) throw err;
console.log(`Server listening on port ${config.app.port}`)
})
module.exports = app;
I am getting this error:
D:\api-rest-carlos-azaustre\node_modules\express\lib\router\route.js:202
throw new Error(msg);
^
Error: Route.get() requires a callback function but got a [object
Undefined]
at Route. [as get] (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\route.js:202:15)
at Function.proto. [as get] (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:510:19)
at Object. (D:\api-rest-carlos-azaustre\routes\private.js:6:8)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object. (D:\api-rest-carlos-azaustre\settings\app.js:15:23)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18) [nodemon] app crashed - waiting for file changes before starting...
And sometimes this line is added at the top of error:
(node:3092) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 exit listeners > added to [Bus]. Use emitter.setMaxListeners() to increase limit
After reading the answers, I edit my question. I have placed only auth and not auth.isAuth and I am getting the following error:
D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a
Object
at Function.use (D:\api-rest-carlos-azaustre\node_modules\express\lib\router\index.js:458:13)
at Function. (D:\api-rest-carlos-azaustre\node_modules\express\lib\application.js:220:21)
at Array.forEach ()
at Function.use (D:\api-rest-carlos-azaustre\node_modules\express\lib\application.js:217:7)
at Object. (D:\api-rest-carlos-azaustre\settings\app.js:20:5)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object. (D:\api-rest-carlos-azaustre\index.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14) [nodemon] app crashed - waiting for file changes before starting...
Does anybody know what is it due to?
module.exports = isAuth; means you're only exporting the function and nothing else. That means when you do const auth = require('../middlewares/auth');, auth is the actual function, not an object containing isAuth as a property.
So, doing router.get('/', auth, (req, res) => { should work, instead of auth.isAuth which is invalid.
Learn more about modules here: https://js.evie.dev/modules
Yes, you export the function with this code: module.exports = isAuth;
But then you call use it like this: auth.isAuth
Assuming you're doing something like const auth = require('./bin/auth.js'); or whatever
auth would be the function itself -- there will be no isAuth property.
So you should try this:
router.get('/', auth, (req, res) => {
You haven't posted your entire code, so this is just a best guess.

Export module correctly with working functions. Node js

I want to export some module to my app.js and use it. But i catch an exception like:
'getUserFromDB isnt defined'
So, that's my app.js:
var api = require('./routes/API')
app.use(api.router)
And API.js:
const router = require('express').Router()
function getUserFromDB(login){
// some actions
}
router.get('/get-db', (req, res) => {
getUserFromDB('abcde123')
})
module.exports = {
router: router,
getUserFromDB: getUserFromDB
}
Full Stack trace:
Trace: Trace before app.use(api.router)
at Object.<anonymous> (\my-project\build\dev-server.js:74:9)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:502:3
ReferenceError: getUserFromDB is not defined
at NativeConnection.<anonymous> (\my-project\build\dev-server.js:65:5)
at NativeConnection.g (events.js:292:16)
at emitNone (events.js:86:13)
at NativeConnection.emit (events.js:185:7)
at open (\my-project\node_modules\mongoose\lib\connection.js:686:11)
at NativeConnection.Connection.onOpen (\my-project\node_modules\mongoose\lib\connection.js:695:5)
at \my-project\node_modules\mongoose\lib\connection.js:655:11
at \my-project\node_modules\mongoose\lib\drivers\node-mongodb-native\connection.js:71:5
at \my-project\node_modules\mongodb\lib\db.js:238:5
at Server.connectHandler (\my-project\node_modules\mongodb\lib\server.js:324:7)
at Server.g (events.js:292:16)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at \my-project\node_modules\mongodb-core\lib\topologies\server.js:300:14
at \my-project\node_modules\mongodb-core\lib\connection\pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
\my-project\node_modules\mongodb\lib\server.js:327
process.nextTick(function() { throw err; })
I dont know what to do.
Please try the following
const router = require('express').Router()
function getUserFromDB(login){
// some actions
return login;
}
router.get('/get-db', (req, res) => {
res.send(getUserFromDB('abcde123'));
})
module.exports = {
router: router,
getUserFromDB: getUserFromDB
}
Change to the following in app.js
app.use('/', api.router);
const router = require('express').Router()
const getUserFromDB = function(login){
// some actions
}
router.get('/get-db', (req, res) => {
getUserFromDB('abcde123')
})
module.exports = {
router: router,
getUserFromDB: getUserFromDB
}

'<' not recognized when using reactJS in server-side node.js

I want to pass React Component from server-side, which is written in node.js.
Code(server.js):
var ReactDOMServer = require('react-dom/server');
var ReactApp = require('./console/ReactApp');
app.get('*', function(req, res, next){
var reactHtml = ReactDOMServer.renderToString(<ReactApp />);
res.render('index',
{reactOutput: reactHtml});
});
console/ReactApp.js:
var React = require('react');
var ReactApp = React.createClass({
render: function() {
return <div>Hello World</div>;
}
});
module.exports = ReactApp;
In both files, '<>' generated SyntaxError when running node server.js
var reactHtml = ReactDOMServer.renderToString(<ReactApp />);
^
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/.../www.js:7:11)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
that's is JSX. You need to transpile it before use or run it with babel-node (the latter is NOT a recommended method).
Or you can use transpiled code like this:
var reactHtml = ReactDOMServer.renderToString(React.createElement(ReactApp));
See full api of React.createElement here

Mongoose Mixed Schema not working

I am trying to set mixed Schema in ExpressJs I tried to use mongoose.Schema.Types.Mixed didnĀ“t worked and tried explicit as shown bellow but unfortunately it fails with same error:
"C:\Program Files (x86)\JetBrains\WebStorm 9.0.3\bin\runnerw.exe"
"C:\Program Files (x86)\nodejs\node.exe" app.js
c:\Users\User\Desktop\nodekid\node_modules\node-restful\lib\model.js:247
app.getDetail = app.get;
^ TypeError: Cannot read property 'get' of undefined
at Function.Model.register (c:\Users\User\Desktop\nodekid\node_modules\node-restful\lib\model.js:247:22)
at Object. (c:\Users\User\Desktop\nodekid\routes\api.js:10:8)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (c:\Users\User\Desktop\nodekid\app.js:18:17)
at Module._compile (module.js:456:26)
Process finished with exit code 8
/**
* Created by User on 3/8/2015.
*/
var restful = require("node-restful");
var mongoose = restful.mongoose;
var storeSchema = new mongoose.Schema({
name: String,
products: [new mongoose.Schema({
name : String,
description : String
})]
});
module.exports = restful.model("store", storeSchema);
/**
* Created by User on 3/8/2015.
*/
var express = require("express");
var router = express().Router;
var stores = require ("../models/store");
stores.methods(["get","post","put","delete"]);
stores.register(router,"stores");
module.exports = router;
New Error:
c:\Users\User\Desktop\nodekid\node_modules\node-restful\lib\model.js:228
app[key](prefix + '/:id([0-9a-fA-F]{0,24}$)?', handlerlist);
^ TypeError: Object function createApplication() { var app = function(req, res, next) {
app.handle(req, res, next); };
mixin(app, EventEmitter.prototype, false); mixin(app, proto,
false);
app.request = { proto: req, app: app }; app.response = {
proto: res, app: app }; app.init(); return app; } has no method 'get'
at Function.Model.registerRoutes (c:\Users\User\Desktop\nodekid\node_modules\node-restful\lib\model.js:228:17)
at Function.Model.register (c:\Users\User\Desktop\nodekid\node_modules\node-restful\lib\model.js:248:8)
at Object. (c:\Users\User\Desktop\nodekid\routes\api.js:10:8)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (c:\Users\User\Desktop\nodekid\app.js:18:17)
The error was in api.js in setting routing:
var router = express().Router;
Just Change it with:
var router = express.Router();

Node js , Error: can not find module

Here is the error which I get when I run nodejs app.js
module.js:340
throw err;
^
Error: Cannot find module 'share'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/quicksilver/project/master/app.js:3:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
I am repeatedly getting this error :
I have already done npm install -g share several times ,but it has been no use.
var express = require('express')
var sharejs = require('share')
var connect = require('connect')
var AWS = require('aws-sdk');
//var zmq = require('zmq');
var app = express();
app.set('view options', {layout: false});
var problem={};
var sharejs_server;
AWS.config.loadFromPath('./awsconfig.json');
locomotive.boot('.', app.settings.env, function(err, app) {
var options = {};
if (err) { throw err; }
options.db = app.locals.db;
sharejs_server = sharejs.server.attach(app, options);
app.listen(app.locals.port, app.locals.ip, function () {
var addr = this.address();
console.log('listening on %s:%d', addr.address, addr.port);
});
});

Categories

Resources