I am getting app.use() requires a middleware function error when using Express edge package in npm. I am using this - https://github.com/ecrmnn/express-edge
I followed and read the documentation but I can't seem to find what else does the function require
Here is the code.
const path = require('path');
const expressEdge = require('express-edge');
const express = require('express');
const app = new express()
app.use(express.static('public'));
app.use(expressEdge);
app.set('views', `${__dirname}/views`);
app.get('/', (req, res) => {
res.render('index');
})
app.get('/about', (req, res) => {
res.sendFile(path.reso0lve(__dirname, 'pages/about.html'))
})
app.get('/post', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/post.html'))
})
app.get('/contact', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/contact.html'))
})
app.listen( 4000, () => {
console.log('App has started')
})
Here is the error:
E:\NODE-JS-BLOG\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (E:\NODE-JS-BLOG\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (E:\NODE-JS-BLOG\index.js:11:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
app.use() requires a middleware function[nodemon] restarting due to changes...
Did you mean expressEdge.engine ?
const path = require('path');
const {engine} = require('express-edge');
const express = require('express');
const app = new express()
app.use(express.static('public'));
app.use(engine);
app.set('views', `${__dirname}/views`);
Related
while running my first MEAN stack application i am getting this error:
\contactlist\node_modules\express\lib\router\index.js:502
this.stack.push(layer);
^
TypeError: Cannot read property 'push' of undefined
at Function.route (C:\Users\Mahima Kaushik\Desktop\contactlist\node_modules\express\lib\router\index.js:502:14)
at Function.proto. [as post] (C:\Users\Mahima Kaushik\Desktop\contactlist\node_modules\express\lib\router\index.js:509:22)
at Object. (C:\Users\Mahima Kaushik\Desktop\contactlist\routes\route.js:11:8)
at Module._compile (internal/modules/cjs/loader.js:1251:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
at Module.load (internal/modules/cjs/loader.js:1100:32)
at Function.Module._load (internal/modules/cjs/loader.js:962:14)
at Module.require (internal/modules/cjs/loader.js:1140:19)
at require (internal/modules/cjs/helpers.js:75:18)
at Object. (C:\Users\Mahima Kaushik\Desktop\contactlist\app.js:9:15)
at Module._compile (internal/modules/cjs/loader.js:1251:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
at Module.load (internal/modules/cjs/loader.js:1100:32)
at Function.Module._load (internal/modules/cjs/loader.js:962:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
contactlist/app.js
var express = require('express');
var mongoos = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//connect to mongodb
mongoos.Mongoose.connect('mongodb://localhost:27017/contactlist');
//on connection
Mongoose.connection.on('connected',()=>{
console.log('connected to database mongodb #2717');
});
Mongoose.connection.on('error',(err)=>{
if(err)
{
console.log('error in database connection:'+err);
}
});
//port number
const port = 3000
//adding middleware -cors
app.use(cors());
//boday-parser
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname,'public')));
//add routes
app.use('/api',route);
//testing
app.get('/',(req,res)=>{
res.send('contactlist');
});
app.listen(port,()=>{
console.log('server started at port:'+port);
});
contactlist/routes/route.js
const { Router } = require('express');
const express = require("express");
const router = express.Router();
//retrieving contacts
router.get('/contacts',(req,res,next) =>{
res.send('retrieving the contact list');
});
//add contacts
Router.post('/contact',(req , res, next)=>{
//logic
});
//delete contacts
Router.delete('/contact/:id',(req , res, next)=>{
//logic
});
module.exports = router;
You didn't create route correctly. The .get, .post and .delete are instance methods of Router instance, NOT static method. For more info, see Routing
routes/route.js should be:
const { Router } = require('express');
const router = Router();
//retrieving contacts
router.get('/contacts', (req, res, next) => {
res.send('retrieving the contact list');
});
//add contacts
router.post('/contact', (req, res, next) => {
//logic
});
//delete contacts
router.delete('/contact/:id', (req, res, next) => {
//logic
});
module.exports = router;
I'm creating blog using node js and following this tutorial https://vegibit.com/node-js-blog-tutorial/ but now I stuck it gives me error on app.use('express-edge') here is my code
const path = require('path');
const expressEdge = require('express-edge');
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = new express();
mongoose.connect('mongodb://localhost:27017/node-blog', {
useNewUrlParser: true
})
.then(() => 'You are now connected to Mongo!')
.catch(err => console.error('Something went wrong', err))
app.use(express.static('public'));
app.use(expressEdge);
app.set('views', __dirname + '/views');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', (req, res) => {
res.render('index');
});
app.get('/posts/new', (req, res) => {
res.render('create')
});
app.post('/posts/store', (req, res) => {
console.log(req.body)
res.redirect('/')
});
app.listen(4000, () => {
console.log('App listening on port 4000')
});
and my error looks like
[nodemon] starting node index.js
C:\Users\91762\Desktop\Blog\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\91762\Desktop\Blog\node_modules\express\lib\application.js:210:11)
at Object. (C:\Users\91762\Desktop\Blog\index.js:16:5)
at Module._compile (internal/modules/cjs/loader.js:945:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
at Module.load (internal/modules/cjs/loader.js:798:32)
at Function.Module._load (internal/modules/cjs/loader.js:711:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:1014:10)
at internal/main/run_main_module.js:17:11
[nodemon] app crashed - waiting for file changes before starting...
Maybe the tutorial is out of date, newest version of express-edge does not export edge engine as default export, the package exports a object what includes config, engine.
You can follow package document if your node version support object destructuring.
...
const { engine } = require('express-edge');
...
app.use(engine);
...
Or, just change a little in your code:
app.use(expressEdge.engine); // instead of app.use(expressEdge);
Use it like a handler is the best choice.
app.use(expressEdge.engine);
I'm trying to catch the post data from my form and when I'm done with processing I want it to render the index.html file again.
Although when I'm trying the code as displayed below, I get an error.
The error:
Error: Cannot find module 'html'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at new View (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/view.js:81:14)
at Function.render (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/application.js:570:12)
at ServerResponse.render (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/response.js:1008:7)
at /Applications/XAMPP/xamppfiles/htdocs/controlpanel/server.js:14:9
at Layer.handle [as handle_request] (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/router/layer.js:95:5)
at next (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/router/route.js:137:13)
The code:
var express = require('express');
var session = require('express-session');
var app = express();
app.use('/public', express.static('public'));
app.use( express.static('public/html') );
app.post('/', function(req, res, next) {
console.log('start processing postdata...');
next()
});
app.all('/', function(req, res) {
res.render('html/index.html');
});
app.listen(2222);
Everything works fine for the GET method.
Only the POST request is causing this error.
What am I doing wrong?
Thanks in advance, Laurens
Here is the working code, you should use sendFile instead if render. Render is been used with views.
'use strict';
let express = require('express');
// let session = require('express-session');
let app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/public', express.static('public'));
app.use(express.static('public/html'));
app.post('/', function (req, res, next) {
console.log('start processing post data...');
next();
});
app.all('/', function (req, res) {
res.sendFile('./index.html', {
root: __dirname + '/public/html'
});
});
app.listen(2222);
I want to implement SMS verification on a Node.js Server that when I am sending request to a URL with user phone number I could send verification SMS to that phone number, I read the documentation here and still, there is an error when I want to import sinch to my app
like codes below
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 5000;
const path = require('path');
const fetch = require('node-fetch');
var APPLICATION_KEY = 'MYAPP_KEY' ;
var SinchClient = require('sinch-rtc');
var sinchClient = new SinchClient({
applicationKey: APPLICATION_KEY,
capabilities: {messaging: true},
onLogMessage: function(message) {
console.log(message);
}
});
sinchClient.start(CREDENTIALS).then(function() {
console.log('Success!');
})
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.static(path.join(__dirname, 'public')))
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', (req, res) => res.render('pages/index'))
.get('/test', (req, res) => {
//mycodes to verify phone number
})
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
it will give me this error
(function (exports, require, module, __filename, __dirname)
{ function Notification(e,t,i,n){this.progress=e/t,this.message=i,this.object=n}function getBrowserInfo(){var e,t=navigator.userAgent,i=t.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||t.match(/(applewebkit(?=\/))\/?\s*(\d+)/i)||[];return/trident/i.test(i[1])?"IE "+((e=/\brv[ :]+(\d+)/g.exec(t)||[])[1]||""):"Chrome"===i[1]&&null!=(e=t.match(/\bOPR\/(\d+)/))?"Opera "+e[1]:(i=i[2]?[i[1],i[2]]:[navigator.appName,navigator.appVersion,"-?"],null!=(e=t.match(/version\/(\d+)/i))&&i.splice(1,1,e[1]),i.join("/").substring(0,50))}function getPlatformInfo(){return navigator.platform}
function Sinch(e){if(!e)throw new TypeError("Could not create SinchClient, configuration not provided.");if(e.capabilities=e.capabilities||{},"string"!=typeof e.applicationKey)throw new TypeError("Could not create SinchClient, applicationKey is not a string");this.c
TypeError: Cannot read property 'indexOf' of undefined
at new Sinch (C:\Users\user\project\node_modules\sinch-rtc\lib\sinch.node.min.js:1:1741)
at Object.<anonymous> (C:\Users\user\project\server.js:9:13)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
Thanks in Advance
To send sms you should not set messaging to to true, in fact i would use this for node
https://www.npmjs.com/package/sinch-verification
I have looked on the forums and have tried fixing everything I could, but still can't seem to get it to work. I am wanting to use router instead of having to use app.get. I have another project in which I am doing the same thing and it works just fine. So I am a little confused as to why this one isn't working. Thank you very much.
Here is my app.js:
var express = require("express");
var app = express();
var indexRoutes = require("./routes/index.js");
app.use("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use("/", indexRoutes);
app.listen(process.env.PORT, process.env.IP, function() {
console.log("server started on port : " + process.env.PORT);
});
Here is the route I am using:
var express = require("express");
var router = express.Router();
var multer = require("multer");
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads');
},
filename: function(req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({storage: storage}).single('userPhoto');
router.get("/", function(req, res) {
res.render("index");
});
router.post("/uploads", function(req, res) {
upload(req, res, function(err) {
if(err) {
return res.send("error uploading file");
}
res.end("file is uploaded");
});
});
module.exports = router;
This obviously isn't right:
app.use("view engine", "ejs");
It should be:
app.set("view engine", "ejs");
FWIW, if you closely look at the stack trace that accompanied the error, you would have found the exact line in app.js that triggered the error:
TypeError: Router.use() requires middleware function but got a string
at Function.use (/private/tmp/node_modules/express/lib/router/index.js:458:13)
at EventEmitter.<anonymous> (/private/tmp/node_modules/express/lib/application.js:220:21)
at Array.forEach (native)
at EventEmitter.use (/private/tmp/node_modules/express/lib/application.js:217:7)
at Object.<anonymous> (/private/tmp/t/app.js:5:5) <--- there!
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)
i think you have to change this line:
app.use("/", indexRoutes);
with this:
app.use(indexRoutes);
more infos here: TypeError: Router.use() requires middleware function but got a Object
change this
app.use("view engine", "ejs");
to
app.set("view engine",'ejs');