I already installed Express, Nodeman, Express-Edge. I using Windows 10.
Someone who had a similar problem with me was told that he needed to install the library he had specified. Like I said I already installed it.
in index.js codes;
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.resolve(__dirname, 'pages/about.html'));
});
app.get('/contact', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/contact.html'));
});
app.get('/post', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/post.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
});
command shell saying:
C:\Users\Maximus\WebstormProjects\untitled4\nodejs-blog-tutorial\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\Maximus\WebstormProjects\untitled4\nodejs-blog-tutorial\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (C:\Users\Maximus\WebstormProjects\untitled4\nodejs-blog-tutorial\index.js:8:5)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...
package.json
{
"name": "nodejs-blog-tutorial",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"keywords": [
"blog"
],
"description": "",
"dependencies": {
"express": "^4.17.1",
"express-edge": "^2.0.2",
"nodemon": "^2.0.4",
"startbootstrap-clean-blog": "^5.0.9"
}
}
It appears you aren't using the right export from the express-edge library. Per the documentation, it should be this:
const express = require('express');
const expressEdge = require('express-edge');
const app = new express();
app.use(expressEdge.engine);
Or, you could do it like this:
const express = require('express');
const { config, engine } = require('express-edge');
const app = new express();
app.use(engine);
The idea here is that expressEdge exports an object that has two properties config and engine and you have to access those properties in order to use the library properly.
Related
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 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`);
I've deployed a React/Express app on Heroku. I'm using BrowserRouter. Everything worked fine locally. My issue is the backend routes are not working. The only route that works is the catchall route. The catchall route is also being called three times for some reason. I console logged the request path using 'req.path' to see which path was being called. It should have been '/google'. Instead the three calls give three different logs for req.path. They are: '/static/css/main.814455d3.chunk.css.map', '/static/js/main.06bdb7f0.chunk.js.map', '/static/js/1.1baafe13.chunk.js.map'. I'm hoping someone can help.
I've been stuck for over a day now. Here are my package.json and static.json from the client side:
static.json
{
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
package.json
{
"name": "workout_tracker",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"jw-paginate": "^1.0.2",
"jw-react-pagination": "^1.0.7",
"normalize.css": "^8.0.0",
"query-string": "^6.2.0",
"random-id": "0.0.2",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"react-headroom": "^2.2.2",
"react-icons-kit": "^1.1.6",
"react-redux": "^5.0.7",
"react-router-dom": "^4.3.1",
"react-scripts": "^2.0.5",
"react-swipe-to-delete-component": "^0.3.4",
"react-swipeout": "^1.1.1",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"redux-devtools-extension": "^2.13.5"
},
"proxy":"localhost:4000",
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
And this is my package.json from express
{
"name": "expresstest",
"version": "1.0.0",
"description": "app to test express and mysql",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start":"node app.js",
"heroku-postbuild": "cd client && npm install && npm run build"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"connect-flash": "^0.1.1",
"cookie-session": "^2.0.0-beta.3",
"cors": "^2.8.4",
"express": "^4.16.3",
"mysql": "^2.16.0",
"passport": "^0.4.0",
"passport-google-oauth20": "^1.0.0"
}
}
This is part of the code from the server. I omitted the other routes as none besides the catchall route are being called anyway.
let express = require("express");
let cors= require("cors");
let mysql = require("mysql");
const util = require("util");
const keys = require("./config/keys");
const passport = require("passport");
const passportSetup = require("./config/passport-setup");
const bodyParser = require("body-parser");
const flash= require("connect-flash");
const path= require("path");
console.log("process env");
console.log("-------");
console.log(process.env.PWD);
const cookieSession = require("cookie-session");
let app = express();
app.use(bodyParser.json());
app.use(cookieSession({
maxAge:24 * 60 * 60 * 1000,
keys:[keys.session.cookieKey]
}));
app.use(passport.initialize());
app.use(passport.session());
if (process.env.NODE_ENV === 'production') {
console.log("inside prod");
app.use(express.static('client/build'));
}
let connection =keys.connection;
app.get("/google", passport.authenticate("google",{
scope:['profile'],
failureFlash:"failure"
}),(req,res)=>{
// console.log(req.flash());
console.log("/google route");
});
const port = process.env.PORT || 4000;
let http = require("http");
let server = http.createServer(app,(req,res)=>{
res.writeHead(200, {"Access-Control-Allow-Origiin": "*"})
});
app.get('/*', (req, res) => {
console.log("catchall");
console.log(req.hostname);
console.log(req.path);
console.log(path.join(__dirname + '/client', 'build', 'index.html'));
res.sendFile(path.join(__dirname + '/client', 'build', 'index.html'));
})
server.listen(port, ()=>{
console.log("Listening on "+ port)
});
Here is my folder structure:
Link to pic of my folder structure
EDIT: I got it working, here is the code that works. I don't know why it works, though. I just tried some things I found on blogs for React/Express/Heroku projects. If anyone can tell me why it works it would be greatly appreciated.
let express = require("express");
let cors= require("cors");
let mysql = require("mysql");
const util = require("util");
const keys = require("./config/keys");
const passport = require("passport");
const passportSetup = require("./config/passport-setup");
const bodyParser = require("body-parser");
const flash= require("connect-flash");
const path= require("path");
console.log("process env");
console.log("-------");
console.log(process.env.PWD);
const cookieSession = require("cookie-session");
let app = express();
app.use(bodyParser.json());
app.use(express.static(__dirname));
app.use(cookieSession({
maxAge:24 * 60 * 60 * 1000,
keys:[keys.session.cookieKey]
}));
app.use(passport.initialize());
app.use(passport.session());
if (process.env.NODE_ENV === 'production') {
console.log("inside prod");
app.use(express.static('client/build'));
}
let connection =keys.connection;
app.get("/google", passport.authenticate("google",{
scope:['profile'],
failureFlash:"failure"
}),(req,res)=>{
// console.log(req.flash());
console.log("/google route");
});
const port = process.env.PORT || 4000;
let http = require("http");
let server = http.createServer(app,(req,res)=>{
res.writeHead(200, {"Access-Control-Allow-Origiin": "*"})
});
app.get("/service-worker.js", (req, res) => {
res.sendFile(path.join(__dirname + "/client","build", "service-worker.js"));
});
app.get('/*', (req, res) => {
console.log("catchall");
console.log(req.hostname);
console.log(req.path);
console.log(path.join(__dirname + '/client', 'build', 'index.html'));
res.sendFile(path.join(__dirname + '/client', 'build', 'index.html'));
})
server.listen(port, ()=>{
console.log("Listening on "+ port)
});
I want to use Mikronode with Express Js but get an error TypeError: _sentence$.get(...).do is not a function for the first run.
I generate the application skeleton using Express generator and try the example Mikronode code from wiki.mikrotik.com
This is the code:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var api = require('mikronode');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// Mikronode example code
var connection = new api('192.168.0.1','admin','password');
connection.connect(function(conn) {
var chan=conn.openChannel();
chan.write('/ip/address/print',function() {
chan.on('done',function(data) {
var parsed = api.parseItems(data);
parsed.forEach(function(item) {
console.log('Interface/IP: '+item.interface+"/"+item.address);
});
chan.close();
conn.close();
});
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
If i run the code above, the output show an error:
/Users/me/Desktop/mknode/node_modules/mikronode/dist/mikronode.js:474
_parsed$.set(this, _sentence$.get(this).do(function (d) {
^
TypeError: _sentence$.get(...).do is not a function
at new SocketStream (/Users/me/Desktop/mknode/node_modules/mikronode/dist/mikronode.js:474:52)
at MikroNode.connect (/Users/me/Desktop/mknode/node_modules/mikronode/dist/mikronode.js:330:30)
at Object.<anonymous> (/Users/me/Desktop/mknode/app.js:31:12)
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 Module.require (module.js:587:17)
at require (internal/module.js:11:18)
error Command failed with exit code 1.
My package.json:
{
"name": "mknode",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.3",
"core-decorators": "^0.20.0",
"debug": "~2.6.9",
"express": "~4.16.0",
"http-errors": "~1.6.2",
"mikronode": "^2.3.11",
"morgan": "~1.9.0",
"pug": "2.0.0-beta11",
"rxjs": "^6.2.2"
}
}
Anyone can help me to solve this?
solved by installing "rxjs": "^5.3.0"
I've created a lambda function handler in NodeJS with Serverless. When I use the command: serverless offline start, I don't get any error. However when I want to deploy the app with the command serverless deploy, it deploys fine. When I want go to the endpoint, I'm getting an internal server error, this happens only when I require camaro in my application. I need the camaro library to create a template from XML.
I tried using node 6.10 and remove camaro, and install it with node 6.10. This doesn't make a difference.
This is the error I can view in Cloud watch:
module initialization error: Error at Error (native) at
Object.Module._extensions..node (module.js:597:18) at Module.load
(module.js:487:32) at tryModuleLoad (module.js:446:12) at
Function.Module._load (module.js:438:3) at Module.require
(module.js:497:17) at require (internal/module.js:20:19) at
Object. (/var/task/node_modules/camaro/index.js:4:16) at
Module._compile (module.js:570:32) at Object.Module._extensions..js
(module.js:579:10)
This is my index.js
const serverless = require('serverless-http');
///
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
//serverless
module.exports.handler = serverless(app);
This is my serverless.yml
# serverless.yml
service: lambda-dashboardcb
provider:
name: aws
runtime: nodejs6.10
stage: dev
region: eu-west-1
functions:
app:
handler: index.handler
events:
- http: ANY /
- http: 'ANY {proxy+}'
plugins:
- serverless-offline
This is my package.json
package.json
{
"name": "lambda-dashboardcb",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon ./bin/www"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.17.1",
"body-parser": "^1.18.2",
"camaro": "^2.2.2",
"cookie-parser": "^1.4.3",
"debug": "~2.6.9",
"express": "^4.15.5",
"google-oauth-jwt": "^0.2.0",
"googleapis": "^23.0.0",
"morgan": "^1.9.0",
"pug": "^2.0.0-beta11",
"serve-favicon": "^2.4.5",
"serverless-http": "^1.5.2"
},
"devDependencies": {
"nodemon": "^1.13.3",
"serverless-offline": "^3.16.0"
}
}
Router
var express = require('express');
var router = express.Router();
var metadata = require('../public/javascripts/metadata-onix.js');
var path = require("path");
var app = express();
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../public', 'index.html'));
});
router.param('isbn', function (req,res,next){
next();
});
router.get('/metadata:isbn', function(req,res,next){
/**
- Get ISBN From URL
- Get Metadata from ISBN, return as JSON
**/
var isbn = req.params.isbn;
var info = metadata.getMetadataOnix(isbn).then(function(info) {
res.json({ cover : info });
});
});
module.exports = router;
Module which uses Camaro
const axios = require('axios');
const transform = require('camaro');
exports.getMetadataOnix = function (id) {
/**
- Create template
- Get request to content CB API.
- Transform data with template.
- Return data.
**/
const template = {
template stuff...
}
return axios({
method: 'get',
url: 'APIURL'+id,
transformResponse: [function (data) {
"use strict";
data = transform(data, template);
return data;
}],
// No .catch here
}).then(function(resp){
console.log('Cover from book:'+JSON.stringify(resp.data));
return resp.data;
});
}
camaro is a native module. you will need to install correct prebuilt binary for AWS Lambda.
Even though you switch to Node 6.10 locally but the binary installed on your machine is built for your platform only, which maybe different with the platform on AWS Lambda.
In order to use camaro on AWS Lambda, you should download a copy of prebuilt camaro from Releases and put to this folder path node_modules/camaro/lib/binding/camaro.node.
As of currently, AWS Lambda only supports node 6 on Linux so you're looking for camaro-v2.1.0-node-v48-linux-x64.tar.gz.
Lambda already supports Node 8 now so choose the prebuilt binary accordingly.