getting 404 on my Express app after deployment - node.js

I have an app that run normally in local development but when I deploy it (Ubuntu 21.x server) I run node/pm2 start (even installed nodemon to try) I get 404 error(not my 404 page). That how I deployed it after logging to server:
sudo apt update
sudo apt upgrade
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
git clone (repo)
cd (repo)
npm install
then I run it with
node app.js
//or
pm2 start app.js
//even using nodemon
nodemon app.js
and I installed Nginx and I get their welcoming HTML when I refer to IP address but I get 404 when I go the project port 3000
that's my server code except the POST req:
const express = require('express');
const helmet = require('helmet');
const compression = require('compression');
const bodyParser = require('body-parser');
// express app
const app = express();
app.use(helmet);
app.use(compression());
// bodyparser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// listen for request
app.listen(process.env.PORT || 3000);
// miidleware static files
app.use(express.static('public'));
app.use(express.static('script'));
app.get('/', (req, res) => {
res.sendFile('./views/index.html', { root: __dirname });
});
app.use((req, res) => {
res.status(404).sendFile('./views/404.html', { root: __dirname });
});
spent around 12 days trying so would appreciate help very much.

It seems that the server you have deployed on has an open port 80, but not port 3000.
If you want to access your express app via port 3000, you need to open the port on the Ubuntu server. How to do this depends on a vast number of variables from where the server is located to what firewall you are using.
If what you are trying to do is have your express app shown by Nginx on port 80, you will need to create a reverse proxy using Nginx.
To do this, read up on this here. There are too many variables for us to help further

Related

How to deploy the node.js application on server with different node version

I want to deploy my node app on server. but when I upload the node app to our server and then add node.js instalation then It is not opening the file. the index.js file is
const connectToDb = require("./DBconfig");
const express = require('express')
const router = express.Router();
var cors = require('cors');
connectToDb();
const app = express();
const port = process.env.PORT | 5000;
app.use(cors());
app.use(express.json());
connectToDb();
app.use( '/api/user' ,require('./routes/user') );
app.use( '/api/post' ,require('./routes/post') );
app.get('/', (req, res) => {
res.send('The site is start now')
})
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
const path = require("path");
app.get("*",(req,res)=>{
res.sendFile(path.resolve(__dirname,'client','build','index.html'))
})
}
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
The node version in my local machine is v16.14.0 but the node version that the NameCheap is given is v14.18.3
the node installation in Namecheap that I configure is the installation of node
the error message is triggered, when I hit the URL of API API's URL, is the error message. I am unable to find the solution to solve this problem. I read some articles in which the writer tells that this type of error occurs when we use the different node versions in the local machine and on the server machine but I can't do anything because I restrict to use of the v14.18.3 on the server-side but I used the v16.14.0 in my local machine. can anyone tell me the solution to solve this type of problem?
webi is also a great tool. I recommend completely uninstalling node and installing it fresh with webi.
# this will install node and the webi cli
# Linux/Mac
curl -sS https://webinstall.dev/node | bash
# Windows
curl.exe -A "MS" https://webinstall.dev/node | powershell
# then you can run the following to switch versions
webi node#14
See https://webinstall.dev/node/ for more info.
nvm is another useful tool that can help you to control the node version itself, you can use nvm commands to upgrade the node version quite easily.
nvm install <version-number>
nvm use 0.10
using nvm use -nodeversion you can switch your node js version to your server node js version.

node express cannot GET static content

Im running a node app inside of /opt/myapp directory.
I have haproxy in front content switching on path_beg /myapp
backend server is listening on port 3000
directory structure:
/opt/myapp
index.js
package, modules
static
public
myfile.html
const express = require("express");
const path = require('path');
const app = express();
app.listen(3000, () => console.log("listening on 3000 "+__dirname+" "+process.cwd()));
app.use(express.static(__dirname+'/static/public')); //nope
//app.use(express.static('..'+'/static/public')); //nope
//app.use(express.static(path.join(__dirname, '/static/public/'))); //nope
Where __dirname outputs /opt/myapp and process.cwd() outputs /opt/myapp
I tried both concantenation and path.join with same results. Cannot GET myfile.html
curl directly on the server to http://host.com:3000 does work by returning the page,
but from browser (in front of haproxy), http://host.com/myapp/myfile.html does not work.
I suppose that I can remove the /myapp from the path in haproxy on the backend, but is there a way with express that i can account for the base directory?
This worked:
app.use('/myapp/',express.static('static/public'));

Improper Routing when deploying Node.js app to Render VPS

I am deploying a Node.js Express app to a VPS by Render. When I run the app on my local machine, the npm start command does a great job of serving my file when I point the browser to localhost:3001. However, after I deploy, the base directory '/' returns "Not found". I have to point my browser to example.onrender.com/public/index.html.
How do I make sure that example.onrender.com/ routes the request to public/index.html?
Thank you!
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.render('index.html');
});
app.listen(3001);
Actually just had to change "Publish Directory" settings in Render to ./public

Integrating Angular with Nodejs

I tried to connect angular front end with nodejs earlier I ran ng build on public folder of app and then ran localhost:3000. No error was given on compilation but app is broken now. Now do I achieve it? My folder structure is like this
client
public
app.js
client contains all angular code, public contains compiled code of angular
till I have also changed output path to ../public in angular.json.
And here is my app.js:
var express = require('express');
var path= require('path');
var cors = require('cors');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');
var app= express();
var port = 3000;
app.set('view engine','ejs');
//app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, '/views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', routesApi);
app.get('/', (req,res) => {
res.send("Invalid page");
});
app.listen(port, () => {
console.log(`Starting the server at port ${port}`);
});
I think up to now you have a build of a running angular application and perfectly running node.js server.
What you have to do is host your client application. Follow the following steps to get this working.
Install http-server globally on your machine using npm install http-server -g command
Then run http-server /path/to/your/dist/folder. (You should get a dist folder after running ng build --prod)
Then run your node.js server.
And open your browser and go to http://localhost:8080

Howto run google assistand bitcoinInfo example webhook index.js

I am trying to run the google assistant example webhook nodejs application(index.js) on my own server, but don't know what is the webhosting setup for this..
https://codelabs.developers.google.com/codelabs/your-first-action-on-google-with-webhook/#2
What is the environment to run this app on my server? Since it's not running as a listening server, I can't use nginx, node_cgi is not mature with apache, how am I supposed to run this sample?
Excellent point, and you should be sure to file a bug request on the page to indicate it is unclear.
The code, as presented, is meant to run using Google Cloud Functions.
This doesn't mean you can't run it on your own server - just that you need to know how to run a Node.js server outside of your Apache or Nginx environment. I've seen a number of configurations, but typically you'll have the Node.js server application running and listening to a local port and have a proxy between your externally facing web server at a particular path and this port.
But even that isn't sufficient in this case - the code itself doesn't listen on a port - it expects to be handed a request and response object in the form that Express.js with a JSON middleware can handle. To do that, you'll need to have installed the Express.js library and then start listening with code such as:
const express = require('express');
const app = express();
app.use( express.json() );
app.get('/', (req, res) => exports.bitcoinInfo( req, res ));
app.listen(3000, () => console.log('App listening on port 3000!'));
Thanks for the help to #Prisoner and #Ido Green link works even better! The minimum to run the sample I did the following:
Create a new nodejs project with mainfile main.js, install express and actions-on-google
mkdir googleActionServer
cd googleActionServer
npm init
npm install --save actions-on-google
npm install --save express`
Copy the index.js from google and put this into main.js
const express = require('express');
const bitcoinInfo = require("./index");
const app = express();
app.use( express.json() );
app.post('/', (req, res) => bitcoinInfo.bitcoinInfo( req, res ));
app.listen(3000, () => console.log('App listening on port 3000!'));
Start the application by running:
node ./main.js
To test with DialogFlow, download and install ngrok to /usr/local/bin for ex and then run:
ngrok http 3000
Ngrok will give you an url that is accesible from outside and forward the requests to the nodejs app. It will also create a https for you, so copy paste the https address into DialogFlow webhook address and you are set to go

Resources