nodejs connect cannot find static - node.js

NOTE: I have tried other solution given here but it didn't work
A newbie with NodeJs. I am trying to follow AngularJS pro and got stuck with setting up NodeJs server. According to book, I installed nodejs and then installed connect package using
npm install connect
then downloaded angularjs in folder next to nodejs folder. Then wrote server.js file to connect to server. Here is the content of the file:
var connect = require('connect');
connect.createServer(connect.static("../angularjs")).listen( 5000);
When I run this server.js file using:
node server.js
I get following error:
function app(req, res, next){ app.handle(req, res, next); }
merge(app, proto);
merge(app, EventEmitter.prototype);
app.route = '/';
app.stack = [];
return app;
has no method 'static'
at Object.<anonymous> (C:\web\nodejs\server.js:2:36)
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)
at startup (node.js:119:16)
at node.js:906:3
Any ideas guys?
Thanks.

The connect package has made some changes in the latest 3.x version of their code base, moving the static middleware to it's own package. You can view the list of packages that have been moved here.
So you have two options:
Option 1
You can install an older, 2.x version of connect and use that as is:
$ npm install connect#2.X.X
Installing the latest 2.X.X version will allow your current implementation to function properly.
Option 2
You can continue to use the 3.x version of connect, and also add serve-static:
$ npm install serve-static
You would also have to update your server.js file to include the new serve-static module:
var connect = require('connect'),
serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic("../angularjs"));
app.listen(5000);

The answer by dylants is helpful. However, here are the exact steps that I followed in order to resolve the same error.
1. From the command window , change directory to the directory in which you installed nodeJS.
2. After having already ran npm install connect, run:
npm install serve-static
3. Create a file named server.js with the following code:
var connect = require('connect'),
serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic("./angularjs"));
app.listen(5000);
While still in command window, and still in the directory in which you have installed nodeJS, run:
node server.js
Navigate to the URL
http://localhost:5000/test.html
This should work. Here is my directory configuration:
C:\NodeJSInstallLocation\angularjs

var connect = require('connect'),
serveStatic = require('serve-static');
connect().use(
serveStatic("angularjs")
).listen(5000);

You might want to try something like this
var express = require('express');
var app = express();
app.use(express.static('angularjs'));

Try this...
const express = require('express');
const app = express();
const path = require('path');
app.use('',express.static(path.join(__dirname, '/static/')));

Related

Node package 'node-fetch' SyntaxError: Unexpected identifier

I have a problem. I am trying to run my NodeJS script using the command:
node /var/script/NodeJS/test.js
But when I run it, I get the following error:
/var/script/NodeJS/node_modules/node-fetch/src/index.js:9
import http from 'http';
^^^^
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
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 Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/var/script/NodeJS/test.js:2:15)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
I have already run the following commands in the terminal:
cd /var/script/NodeJS
npm install
npm install http
npm install node-fetch
I am running node version: v10.19.0
Here is the code I have that gives the error:
const express = require("express");
const fetch = require('node-fetch');
const app = express();
const PORT = process.env.PORT = 8787;
let router = express.Router();
It's just the imports, but this code already gives the provided error!
I can see both the modules in the node_module folder, so why am I getting this error and how can I fix this?
This can happen if you use a 3.X version of node-fetch and a Node version less than 12.20.0
Because node-fetch from v3 is an ESM-only module.
According to the documents you must install a version 2.X or less
npm install node-fetch#2
rename file extension from .js to .mjs
filename must be: test.mjs
import fetch from 'node-fetch';
const express = require("express");
const app = express();
let router = express.Router();
const PORT = process.env.PORT = 8787;
also keep in mind node-fetch has requriements on node version:
https://github.com/node-fetch/node-fetch/blob/main/package.json#L14
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
run it as: node test.mjs
Bonus: If You don't like to use mjs and etc try to install node-fetch#2.6.5
npm i --save node-fetch#2.6.5

OKTA express middleware - TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type Function. Received type undefined

Just including the following in an app causes the following error.
const { ExpressOIDC } = require('#okta/oidc-middleware');
Full error:
$ node app.js
internal/util.js:257
throw new ERR_INVALID_ARG_TYPE('original', 'Function', original);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type Function. Received type undefined
at promisify (internal/util.js:257:11)
at Object.<anonymous> (/dev/tmpOidc/node_modules/jose/lib/jwk/key/rsa.js:13:25)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/dev/tmpOidc/node_modules/jose/lib/jwk/import.js:9:16)
Steps to reproduce
1. Create a new node app and add express and Okta's oidc middleware
npm init
npm install express --save
npm install --save #okta/oidc-middleware
Create app.js
const express = require('express')
const app = express()
const port = 3000
// const { ExpressOIDC } = require('#okta/oidc-middleware');
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
Run it
node app.js
See how it runs. Finally, uncomment and include the line that sets up the OIDC middleware.
const { ExpressOIDC } = require('#okta/oidc-middleware');
Run the app again and I get the error above shows up.
Solved: Need to run with node v12 not v10
I just published a YouTube video that shows you how to use Okta's OIDC Middleware.
You can find the steps I used here. To summarize:
Create a new project with express-generator and pug: npx express-generator --view=pug
Add a new web app on Okta with http://localhost:3000/callback as the login redirect URI
Install Schematics CLI: npm install -g #angular-devkit/schematics-cli
Install and run OktaDev Schematics with your Okta values:
npm i #oktadev/schematics
schematics #oktadev/schematics:add-auth --issuer=$issuer --clientId=$clientId --
clientSecret=$clientSecret
Start your app and authenticate with Okta: npm start
You can see the result of these steps in this GitHub repo.
Solved. When I posted my question I should've included system information such as the version of Node. I had v10.8.0. Once I updated to v12 the typeerror went away.

NPM Install is not working. Getting Reference Errors

I am in the process of learning Node.js and web dev all together, I am coming from a mobile dev background and haven't coded in a few years.
I cloned a project from github and was planning on building on top of it for a learning project.
I am running npm install to add some dependencies to the project and they seem to be installing properly. They are succesfully being added to the node_modules directory as well as being added as a dependancy to package.json
However when running the app I get these errors
ReferenceError: Multer is not defined
at Object.<anonymous> (/Users/willjamieson/airdrive/app.js:26:21)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
There are other dependancies that are working properly within the app but those are ones that were with the project when I initially forked it.
var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
var multer = require("multer");
var bodyParser = require("body-parser");
var Minio = require("minio");
I added multer bodyParsr and Minio those don't work everything else came with the original clone and work flawlessly when I remove the packages I installed.
Javascript is case sensitive. Your error says Multer is not defined and in your code shown you define var multer = require("multer");
Try var Multer = require("multer");

how to check if i have mongodb installed on my computer

I'm trying to create a RESTful API using Node.js and MongoDB for the first time. I'm new to back end programming.
For some reason am getting this error
module.js:327
throw err;
^
Error: Cannot find module './routes/api'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\xampp\htdocs\rest\server.js:15:17)
at Module._compile (module.js:409:26)
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 Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
[nodemon] app crashed - waiting for file changes before starting...
I am unsure whether MongoDB is installed correctly, but I don't know how to check that.
Please help me, either with the error or how I can to check that I have installed MongoDB correctly.
Here is my server.js
// DEPENDENCIES
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// MongoDB
mongoose.connect('mongodb://localhost/rest_test');
// EXPRESS
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// ROUTES
app.use('/api', require('./routes/api'));
// START SERVER
app.listen(3000);
console.log('API is working on port 3000')
First you need to run MongoDB on your machine use command mongod (if you have a path to mongod.exe in your System PATH Variable)
Install all dependencies for your project with npm install express mongoose body-parser
And Error: Cannot find module './routes/api' Where your api.js file ?
After that you can run your server use node server.js
Since I do not see your file api.js I write it myself for clarity
server.js
// DEPENDENCIES
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// MongoDB
mongoose.connect('mongodb://localhost/rest_test');
// EXPRESS
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// ROUTES
app.use('/api', require('./routes/api'));
// START SERVER
app.listen(3000);
console.log('API is working on port 3000')
routes/api.js
module.exports = function(app, res) {
res.sendFile(process.cwd() + '/routes/index.html');
}
routes/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Hello Node.js</h1>
</body>
</html>
Assuming that you are on Windows:
Check in your program files in C:\ to look for a Mongo folder
To use mongo, you need to start a server on your machine.
To do this, launch mongod.exe in the mongo folder you have found previously.
It should work after the server is started!

how to install new nodejs modules to expressjs project?

Currently I am working on online yaml code editor. I use expressjs framework for it. I want to install yamljs module to it. How do I install it? Because following code line cause to an error.
var YAML = require('yamljs');
This is the code segment
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 routes = require('./routes/index');
var users = require('./routes/users');
var YAML = require('yamljs');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
This is the error
Error: Cannot find module 'yamljs'
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/tharindu/Documents/projects/Group project2/CuubezFinal/app.js:12:12)
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)
I use webstorm for coding. I have installed yamljs module using
npm install yamljs
This library is perfectly using if I run my code manually from the ubuntu terminal. But When I run the expressjs project, It gives above error.
could you provide more information like the error text?
Have you tried
npm install yamljs
to make the module accessible to the node environment?
This library is perfectly using if I run my code manually from the
ubuntu terminal. But When I run the expressjs project, It gives above
error.
Make sure your node_modules folder is available in the same or a more outer directory than the folder of your executing script.

Resources