Can't get 'var express = require("express")' to work - javascript

I am new to js and I am trying to develop a simple node.js-mysql app. No matter what I do I can't get the standard
var express = require("express");
statement to work.
I have installed node.js and express correctly, express is in package.json. I have a local server running. But this simple line will not work.
On the node.js side at Windows command line I have no error but when I go to localhost:3000 on the browser, I get
'Uncaught Error: Module name "express" has not been loaded yet for
context: _. Use require([])' error at js console.
I tried changing it to
require(['express']`, function (express) {}
as suggested at node.js web site but then at the Windows command terminal I get a different error saying like
'expecting a string but received an array....'.
I have tried import instead of require and I have tried every suggestion that I could find on the Internet. I have been blowing my brains for weeks to get this to work with no success. I am so frustrated that I am seriously thinking about giving up all together. If someone can help I will be forever greatfull to him/her.
My main js code is as follows:
var port = 3000;
// Import or load node.js dependency modules.
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");
app.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies.
app.listen(port, () => {
console.log(`server is running at http://127.0.0.1:8887`);
});
app.get('/', function(req, res){
res.sendFile("D:/Behran's files/Web projects/havuzlusite/index.html");
});

Require.JS is for loading AMD modules (and is, honestly, obsolete in today's JS landscape).
Node.js modules are either ECMAScript modules (which use import and export) or CommonJS modules (which use require and module.exports).
Even though both AMD and CommonJS modules use a function named require they are not compatible.
There are methods you can use to run ES modules and CommonJS modules in the browser however they can't replace APIs that are provided by runtimes.
Express.js needs to be able to listen for incoming HTTP requests. Browsers do not provide any mechanism to make that possible. Node.js does.
If you want to run Express.js you have to run it using Node.js and not a browser.
Express.js creates an HTTP server. A browser can make requests to it (e.g. if you type http://127.0.0.1:3000 into the address bar.
(Your code says server is running at http://127.0.0.1:8887 but the port constant is set to 3000).
All your Express.js code must run through Node.js.
You can't send a copy of that code to the browser and run it there too.

Related

How do I globally install a Node.js command-line script on the server?

As a prototype, I’ve written a simple Node.js command-line script which loads a .txt file and outputs the contents. I’ve read many articles which suggest that Node.js scripts are usually executed via the command-line and should be installed globally, so that’s the direction I’ve taken, even if there are other techniques.
For the sake of this query, my globally installed command is called my-prototype.
This all works fine on the desktop but I intend to host this prototype on a server, using Express.
How do I globally install my-prototype on the server and, if that’s possible, will I be able to execute it in the same way as in my local tests, as a child process?:
const { execSync } = require('child_process')
const output = execSync(`${process.execPath} my-prototype`)
console.log(output.toString())
I'm not entirely sure that globally installing command-line scripts is for use on a server and wonder whether that's for desktop use only.
If you need just output the contents, then you do not need a console, or rather: you only need it once, to run nodejs
const fs = require('fs');
const express = require('express');
const app = express();
//
app.get('/', async(req, res)=>{
let fileContains = fs.readFileSync('./package.json', 'utf8');
try{
fileContains = JSON.parse(fileContains);
}catch(e){}
res.json(fileContains);
});
//
app.listen(80);
Also, read a little more about the pm2 module, it's very useful

"Uncaught TypeError: Cannot read property 'prototype' of undefined" error in bundle.js

I am trying to build a simple node.js app. node side is running fine but browser doesn't recognize the require function. To get around this, I am using Browserify. I installed Browserify and ran 'browserify index.js -o bundle.js' command. But when I run the browser side, I get ' Uncaught TypeError: Cannot read property 'prototype' of undefined' error in bundle.js. The error is in following line of bundle.js.
var res = Object.create(http.ServerResponse.prototype)
No matter what I try, I can't fix this so I am ready to give up. Any help will be appreciated.
My index.js is as follows:
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 3000; //Set port to 3000.
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true}));
app.use(cors());
In my index.html, I have following included.
<script src="bundle.js"></script>
<script src="index.js"></script>
Browersify can transpile JavaScript to remove the need for the browser to support a module system although it can't "polyfill" libraries and frameworks that are available to NodeJS, eg. running an HTTP server as in your case using the express module. Those need a proper NodeJS runtime and can't run under a simple browser.
Browsers are meant to connect to web servers, not be web servers themselves!
Browsers' security restrictions will not allow a TCP port to be opened. My suggestion: run the express server as a separate process on a Node.js runtime and use Asynchronous JavaScript and XML (AJAX) to communicate with it.

Node.js file to run a local server with access-control-allow-origin

I have an html file that has resources in it's directory
(example file tree)
index.html
imgs
>img1.jpg
>img2.jpg
>img3.jpg
js
>js1.js
>js2.js
How do I run a node.js server that will allow me to view the HTML file, as well as allow me to access certain websites with the access-control-allow-origin *
I am unfamiliar with node, so the simpler, the better!
Extra: does not necessarily have to be node, just a server that will allow access control
Since You're learning and starting from scratch so it's preferred to learn how it's done than installing supper-pupper swiss knife toolset that will hide the logic from You and make You boring lazy developer.
If You just want to achieve quick result and don't want to learn - You may use serve package that will do what You need.
But if You're learning nodejs from zero to hero so read my answer.
It's better to do simple things.
Let's go (:
Create some folder and inside of it do following commands in terminal (or cmd in windows os):
1) Init app:
npm init
2) Install express module:
npm i --save express
3) Install cors module/middleware:
npm i --save cors
4) Create public folder and put Your html files there
5) Create app.js file in sibling folder with public:
"use strict";
const
express = require('express'),
app = express(),
cors = require('cors');
app.use(cors()); // attach cors middleware (must be set before of most route handlers to populate appropriate headers to response context)
app.use('/', express.static('public'));
app.listen(8080, () => console.log('APP STARTED'));
6) Run it: node app.js
7) Open in browser: http://127.0.0.1:8080
for more stuff search in YouTube for nodejs express tutorials, nodejs mean stack tutorials and etc. (:
For a quick resolution it can also be checked, the Chrome Web server app, for creating local server allowing access to the local files over localhost server.
https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb

What is the easiest way to spin up a node/js app?

I am having trouble building a node/js app with various frameworks. I keep getting the error require is not defined even though I have followed various browserify tutorials to fix it.
To give a flavour of what I want to do. I want the app to be able to be ran on a server and then I can npm install anything and these things work smoothly. I have been using express, firebase etc to handle some of my issues.
This is an extract of my app.js file:
var express = require('express');
var app = express();
var firebase = require('firebase');
app.get('/', function (req, res) {
res.sendFile(__dirname + '/html/index.html');
});
app.get('/welcome', function (req, res) {
res.sendFile(__dirname + '/html/welcome.html');
});
I have tried to use bundle.js to get require working but it still insists it is not defined.
Browserify will let you transpile some code so it will run in the browser.
It won't let you do things which are fundamentally impossible in the browser (such as running an HTTP server as you are trying to do here).
If you want to run code that requires Node JS then you need to run it through Node JS. Typically via node app.js in your command line shell.

browserify Wordnet thesaurus

I am using a thesaurus API (altervista) for my JavaScript web app but I want to be able to make lots of synonym requests without worrying about API quotas, etc. I want to self-host a thesaurus on my web host and I would like to send words and receive their synonyms from JavaScript in the browser.
As research I tried node, and within node I was able to get synonyms with these packages:
"natural" and "wordnet-magic"
so then I tried to browserify "natural" and "wordnet-magic" node packages. On attempting to browserify "natural":
"Error: Cannot find module 'lapack'"
"lapack seems to be a native OS-dependent shared library, so it can't be browserified." https://github.com/moos/wordpos/issues/9
Also I had no luck browserifying "wordnet-magic":
"Uncaught TypeError: Cannot read property '_ansicursor' of undefined"
Possibly related (since sqlite3 is in my wordnet-magic packages), instances of same error reported here but still unresolved: https://github.com/mapbox/node-sqlite3/issues/512
My second choice would be a PHP solution should it be impossible in JavaScript. It does not have to use Browserify or Wordnet, but Wordnet would be such an amazing thing to have in the browser. Thanks.
Okay I can get synonyms in the browser (thanks to Stuart Watt):
I followed instructions to setup a javascript wordnet app here:
https://github.com/morungos/wordnet
then did
npm install express
and then ran this code with node:
var express = require('express');
var app = express();
var WordNet = require('node-wordnet');
var wordnet = new WordNet();
app.get('/lookup', function(req, res) {
wordnet.lookup(req.query.word, function(results) {
res.send(results);
});
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
and you can then see wordnet in your browser, e.g.
http://localhost:3000/lookup?word=wind
It's visible, it works, and to consume it in your html, see this answer:
https://stackoverflow.com/a/36526208/5350539

Categories

Resources