unable To connect in Node js - node.js

I just started learning Node js, First I installed node,npm, express
I want to work in npm, but I don't know how to start. The command I gave in terminal was
sh-4.2$ cd new/
sh-4.2$ express new-project
sh-4.2$ cd new/
sh-4.2$ express new-project
sh-4.2$ node app
But I was not able to connect in localhost:3000

I dislike automatic project generators so here is how to create a new express project manually.
Create new folder:
mkdir myNewApp
cd myNewApp
Create a new package.json (makes managing dependencies much easier) - just press enter to all questions, you can change these things later:
npm init
Install express and save it in our package.json:
npm install express --save
Create our main server file:
touch server.js
And paste the following:
var express = require('express'),
server = express();
server.get('/', function (req, res) {
res.send('hello world');
});
server.listen(3000);
Now start it:
node server.js
And visit http://localhost:3000 in your browser.

Try this command in your project folder after you've generated the project:
node bin/www
The code to run the server is placed in this file.

Related

BASH: express command not recognized

I've read other forums on installing express, I have run
npm install express -g on command prompt as admin.
I did this command a few times and restarted my computer multiple times but Express is still not recognized.
Any help is appreciated.
Express isn't a web server; it is a framework for building web servers.
The express package doesn't provide anything directly executable.
The express documentation has a getting started guide.
If you aren't trying to do server-side programming using Node.js and just want an HTTP server, then the http-server package may be more your speed.
Assuming you’ve already installed Node.js, create a directory to hold your application and make that your working directory.
then follow the below command
npm init
follow step press enter and after
npm install express
make index.js file paste below hello work program.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Now you can run file using below command
node index.js
Open your broswer and enter URL : http://localhost:3000/
You can display Hello World!
You have successfully installed node js and express js program.

How to deploy React application to Heroku

I have built a single-page weather app with React and Node.js but can't seem to get it to deploy to Heroku. So far, I have:
Created a new app on Heroku called weather-app-react-node
Logged into Heroku on the CLI
Run the command 'heroku git:remote -a weather-app-react-node' in my terminal
Added a Procfile with 'web: npm start' in it
Ran 'git add .', 'git commit -m "Pushed to heroku"', 'git push heroku master'
My terminal tells me it is deployed and waiting but when I click on the link, I get this error message:
SecurityError: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.
I've tried to google it but can't seem to find anything relevant to my situation. Anyone know how to fix it?
heroku-site: https://weather-app-react-node.herokuapp.com/github: https://github.com/caseycling/weather-app
To deploy the React app to Heroku, I performed the following steps...
1. In your terminal, enter npm -v and node -v to get your npm and node version. In my case, my npm version is 6.14.1 & my node version is 12.13.0.
2. In package.json, add "main": "server.js", and "engines": { "npm": "6.14.1", "node": "12.13.0" }, under the "private" property. In your scripts property, add "heroku-postbuild": "npm install" and set "start" to "node server.js".
3. In the root directory, create a Procfile with one line of text: web: node server.js.
4. In the root directory, create the server.js file with the below code..
const express = require("express");
// eslint-disable-next-line no-unused-vars
// const bodyParser = require('body-parser');
const path = require("path");
const app = express();
const port = process.env.PORT || 8080;
app.use(express.static(path.join(__dirname, "build")));
// This route serves the React app
app.get('/', (req, res) => res.sendFile(path.resolve(__dirname, "build", "index.html")));
app.listen(port, () => console.log(`Server listening on port ${port}`));
5. Enter npm run build in the terminal to produce the build directory. Next, remove (or comment out) /build from .gitignore file (in root directory).
6. Test if server.js works by entering node server.js (or nodemon server.js) in the terminal. If it works, server.js should serve the React app.
7. Commit everything from step 1-6 to GitHub and Heroku repository. To commit to Heroku repository, in your terminal, enter heroku git:remote -a weather-app-react-node and afterward, enter git push heroku master.
You can try logging in to heroku directly and deploy your github repository's desired branch from there directly.
I used create-react-app-buildpack
npm install -g create-react-app
create-react-app my-app
cd my-app
git init
heroku create -b https://github.com/mars/create-react-app-buildpack.git
or
heroku create -b mars/create-react-app
git add .
git commit -m "I am the newborn app"
git push heroku master
heroku open
Note: In my case, buildpack config from CLI did not work, I still had nodejs-build pack, so I manually changed the build pack to mars/create-react-app in the Heroku project dashboard
The best practice to push React apps to Heroku with a node js backend is to use the Heroku Post Build Script, The post build will take care of all the work under the hood
Follow the steps below
Add This below snippet to your package.json under the scripts
scripts{
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix reactFolderName && npm run build --prefix reactFolderName"
}
And add this snippet to your index.js file
app = express()
app.use(express.static('reactFolderName/build'));
app.get('*', (req, res) => res.sendFile(path.resolve(__dirname, 'reactFolderName', 'build', 'index.html')));
After I set up the all the things above mentioned I'm facing this issue.
When I'm using the URL like http://localhost:8080/ & http://localhost:8080/button
Cannot GET /button
In Console
Failed to load resource: the server responded with a status
of 404 (Not Found)
DevTools failed to load source map: Could not load content
for chrome-
extension://gighmmpiobklfepjocnamgkkbiglidom/browser-
polyfill.js.map: System error: net::ERR_FILE_NOT_FOUND

Starting Angular application as a default of a NodeJS project

I have a NodeJS application and an Angular 6 as a frontend.
The project looks like:
-> Node Project
---> src
---> Client_App (Anuglar)
To run the application, I need to follow those commands and start the server and angular separately, like:
-> node start
-> cd src/Client_App
-> ng serve
I need to start the two application with one single command or to add my dist file of Angular to be run at the start of my NodeJS, which is using Jade right now.
I am still new to NodeJS and still don't know how to configure it.
Anybody can help? Thanks
Edited:
I have tried now to add the dist folder to my views folder and run it within the app.js
app.get('/', function (req, res, next) {
res.sendFile(path.join(__dirname + '/app_server/views/ngapp/index.html'));
});
But I am receiving the error, that my .js and .css folders are not found:
When you build your application with the CLI ng build --prod, you get a dist folder : this folder contains all of your application, bundled into different files (feel free to look at them).
To be able to create a .ZIP file with that, you will need two things :
this dist folder
an http server
You have the first one, but not the second one.
All you need is a very simple server. For instance, http-server on NPM can do that. By installing it as a dev dependency, you could create a command in your package.json file
"deploy-locally": "http-server ./dist"
And now run it with
npm run deploy-locally
Or even better,
"start": "http-server ./dist"
And run with
npm start
If you don't want to use a NPM package (or forced to use NodeJS), simply create a basic http server in a JS file and run it with your command line (sorry, can't help on that, not into nodeJS right now).
You can create a new route and pass in app.route as express.static as below,
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(path.join(__dirname, 'dist')));
make sure, u have build version of angular application by running this command,
ng build --prod --build-optimizer
You would need express to install in this case. express has amazing ways to handle all this

deploying angular universal on node.js express server

angular universal(angular or angular-cli) can be create three part:
browser folder
ng build --prod to generated static file
server folder
A server bundle by script(bundle)
server.js
webpack bundle serve (bundle)
Run node dist/server.js can be work on localhost:4000.
But when I have a node.js(express) server, how can I deploy these files?
If I only have one file by ng build --prod, I can deploy it on node.js like this.
app.js:
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'dist/index.html'));
});
The bundle has its own express embedded, so just start it like you did on your own machine with node server.js.
The recommended way is to use a process manager like pm2. If you want to use pm2, install it with npm i -g pm2 then start your server as a pm2 process with pm2 start server.js

edited files at host, but docker container is not refreshed

I am new to docker, I have successfully installed docker on ubuntu,
I am testing a node app, at folder: /home/samir/Documents/docker-centos:
$ ls
Dockerfile Dockerfile~ index.js index.js~ package.json package.json~
I don't know what are those duplicates ending with ~ as I didn't add them.
index.js:
var express = require('express');
// Constants
var PORT = 8080;
// App
var app = express();
app.get('/', function (req, res) {
// even if I change the output here, I still get Hello world only
res.send('Hello world, This was added\n');
});
app.listen(PORT);
console.log('Running on http://localhost:' + PORT);
Although I have started the container using a data volume that points to the same app dir like this:
docker run -p 49160:8080 -v /home/samir/Documents/docker-centos -d samir/centos-node-hello
but when I view the output like:
curl -i localhost:49160
I get Hello world even if I changed the file..
Do I miss something?
How would I run the container, and edit files at host? why it didn't work?
EDIT
Dockerfile
FROM centos:centos6
# Enable Extra Packages for Enterprise Linux (EPEL) for CentOS
RUN yum install -y epel-release
# Install Node.js and npm
RUN yum install -y nodejs npm
# Install app dependencies
COPY package.json /src/package.json
RUN cd /src; npm install
# Bundle app source
COPY . /src
EXPOSE 8080
CMD ["node", "/src/index.js"]
You need to build the Docker image again using the docker build command
If you're planning on using this setup not only for one-off testing of your app, but for development as well, you'd be better off mounting your application code as a volume.

Resources