app.use() requires a middleware function in express-edge - node.js

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);

Related

TypeError: Cannot read property 'apply' of undefined?

When setting up my router file.
I get
TypeError: Cannot read property 'apply' of undefined at /Users/evibreukers/Desktop/NODEJS/beginnerguide/node_modules/express/lib/router/index.js:635:15
at next (/Users/evibreukers/Desktop/NODEJS/beginnerguide/node_modules/express/lib/router/index.js:210:14)
at Function.handle (/Users/evibreukers/Desktop/NODEJS/beginnerguide/node_modules/express/lib/router/index.js:174:3)
at router (/Users/evibreukers/Desktop/NODEJS/beginnerguide/node_modules/express/lib/router/index.js:47:12)
at Object. (/Users/evibreukers/Desktop/NODEJS/beginnerguide/server.js:20:20)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
The problem is within the express library.
I am not sure where the problem is within my code because I did not use the apply method myself.
/router/index.js
const express = require('express');
const router = express.Router();
router.get('/',function(req,res){
res.render('index.html')
});
router.get('/about',function(req,res){
res.render('about.html');
});
router.get('/all', function (req, res) {
res.send(projectData);
// console.log(req);
});
module.exports.data = data = []
router.post('/addName', function (req, res) {
data.push(req.body);
console.log(data);
});
module.exports = router;
server.js
projectData = {};
// --> npm init (set up package.json)
// --> npm install express
const express = require('express');
const app = express();
app.use(express.static(__dirname + '/static'));
// --> npm install cors
const cors = require('cors');
app.use(cors());
// --> npm install ejs
require('./routes')(app);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// --> npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// connect with routes file
app.use(require('./routes'));
// set up PORT
const port = 3000;
const server = app.listen(port,function(){
console.log(`We have started our server on port ${port}`);
});
/static/app.js
const postData = async ( url = '', data = {})=>{
console.log(data);
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {'Content-Type': 'application/json',},
// Body data type must match "Content-Type" header
body: JSON.stringify(data),
}); // end of respnose
try {
const newData = await response.json();
console.log(newData);
return newData;
}
catch(error) {
console.log("error", error);
}
} // end of postData
postData('/addName', {answer: 'evi'});
The traceback points to the line require('./routes')(app); (if I'm counting my line numbers correctly).
I think you could remove it, since you're doing app.use(require('./routes')); later.
Because you require the module with require('./routes')(app); then, in your module, you need to export a function that takes app as argument:
module.exports = app => {
...
return router;
}
So, the error is probably because you pass an argument to something that does not expect an argument.

Getting app.use require middleware even though I followed the documentation

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`);

Module not found error - NodeJS Express.JS

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);

SMS verification using sinch and node.js server

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

Router.use() requires middleware function but got a string?

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');

Resources