Openshift nodeJS successful deployment, but got "Application is not available" - node.js

I have created simplest nodeJS app and it running locally, but not on OpenShift.
I use Import from Git and the code imported and build successfully.
When I click Open URL in my app, it show "Application is not available" page.
index.js:
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
app.get('/', (req, res) => {
res.send('Hello from Node.js Starter Application!');
});
const PORT = process.env.PORT || 8000;
server.listen(PORT, () => {
console.log(`App started on PORT ${PORT}`);
});
package.json:
{
"scripts": {
"start": "node index.js",
},
"dependencies": {
"express": "^4.18.2",
}
}
The most last from logs:
> node index.js
App started on PORT 8000
What I have missed to successfully run my server on OpenShift?
Thank you

Related

How to fix Node express error: cannot GET

I'm trying to create a simple backend api for an app I'm working on (create-react-app) and decided to use node express. I'm getting the error 'cannot GET' when I open my browser and I don't understand why.
Here is my server/index.js file:
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
app.get("/api", (req, res) => {
res.json({ message: "Hello from server!" });
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
Here is my start script:
"scripts": {
"start": "node index.js"
}
In my console I see this error:
Failed to load resource: the server responded with a status of 404 (Not Found)
This is my folder structure:
I have an app called 1REPMAX that contains the folders
>build
>node-modules
>public
>server
>node_modules
>index.js
>package-lock.json
>package.json
>src
.gitignore
package-locj.json
package.json
So what I've been doing is I cd into server and then run npm start.
When I open my browser to localhost:3001 I get the error. Any help on what I'm doing wrong? If more information is needed just let me know. Also, when I ran npm start the first time it started up fine, but now every time I run it I get this error:
code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 3001
I don't know if this has something to do with it or not.
The first error is caused because your app is not listening to the / path, only the /api path.
The second error is caused by a duplicate app.listen() call in your server/index.js file.
Your code should look something like this in order to resolve the issues:
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
app.get("/", (req, res) => res.send("Main page"));
app.get("/api", (req, res) => {
res.json({ message: "Hello from server!" });
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});

Failed at the app#1.0.0 start script This is probably not a problem with npm. There is likely additional logging output above

Hi Guys, I have created a little project of Mern stack. I am deploying it correctly on Heroku. But as soon as I am checking her on Heroku after deploying, then Failed to load resource: the server responded with a status of 503 (Service Unavailable) error is coming.
But as soon as I run heroku local in cmd after deploying then it is working correctly. I am giving below the heroku setup code. Please guide me. please ........
package.sjon file of backend
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npm install && node index",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"dependencies": {
"config": "^3.3.1",
"express": "~4.16.1",
"express-fileupload": "^1.1.7-alpha.3",
"mongoose": "^5.9.12",
"nodemailer": "^6.4.6"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Index.js file of backend
var express = require('express');
var path = require('path');
const connectDB = require('./config/db')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var studentRouter = require('./routes/student')
var app = express();
connectDB();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('client/build'))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
app.use('/', indexRouter);
app.use('/', studentRouter);
app.use('/users', usersRouter);
if (process.env.NODE_ENV == "production") {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
var port = process.env.PORT || '8000';
app.listen(port, () => {
console.log(`server run port ${port}`);
})
module.exports = app;
All these codes are absolutely correct. I had a problem creating a cluster in mongodb atlas. The problem was that I had selected add current ip address while creating the cluster. Whereas I had to select allow from anywhere. So now I have selected the book. And now it is doing the right thing.
In my case, changing network access form anywhere in my MongoDB cluster, fixed the problem.
Also, don't forget to hit restart all dynos.

Problem when Client (react) and Server(nodejs) are in the same folder

I'm trying to deploy my web application, that has my client and server at the same main folder, to Heroku and I face some annoying problem that the server isn't serving the react build folder.
Here's my project folder tree:
/client
/api
app.js
server.js
app.js => routes, loading models, controllers, etc
server.js => server configuration
Here's the content of server.js, I believe the problem is here
const app = require('./app');
const path = require('path');
const cors = require('cors');
const express = require('express');
app.use(cors())
if (process.env.NODE_ENV === "production") {
console.log('we are on production!')
app.use(express.static('./client/build'));
app.get('*', (req, res) => {
console.log('redirecting to react app build')
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on PORT ${port}`))
It never gets to the console.log('redirecting to the react app build') part
When I entered my heroku server I face the server side instead of my react build. why is that so?
I've just created a test project using your architecture. My project is running and uploaded on Heroku right now. I'm gonna detail all steps I just do to make it works according to given information.
So my project architecture :
client/ // from CRA
package.json
server.js
.env
Configure your environment variable :
heroku config:set NODE_ENV=production // this for production heroku
In my .env file I set local environment variables such as :
NODE_ENV=production
Here's my main package.json file which I defined a heroku-postbuild to create the client build folder.
{
"name": "foo",
"version": "1.0.0",
"main": "index.js",
"license": "mit",
"dependencies": {
"cors": "2.8.5",
"express": "4.17.1",
"path": "0.12.7"
},
"scripts": {
"start": "node server.js",
"heroku-postbuild": "cd client && yarn && yarn build"
}
}
And the server.js file, almost the same as the one provided
const path = require('path');
const cors = require('cors');
const express = require('express');
const app = express()
app.use(cors())
if (process.env.NODE_ENV === "production") {
console.log('we are on production!')
app.use(express.static('client/build'));
app.get('*', (req, res) => {
console.log('redirecting to react app build')
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"))
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on PORT ${port}`))
You can run Heroku in local by typing this command heroku local in will loaded the .env file with environment variables.
To test production Heroku you have to type heroku open. Don't forget to set up "production" environment variable with command I wrote above.
Everything's working fine. I can upload my code to Github if you want me to.

Deploy React App to heroku cannot connect backend

I am trying to deploy my app which using node.js, react and MongoDB to Heroku; The deploy was succeeded; However, the website cannot fetch data from MongoDB.
The error is GET http://localhost:5000/comment net::ERR_CONNECTION_REFUSED and Uncaught (in promise) Error: Network Error, I think it is because I don't have node server.js running in the backend. can anyone help me with how to deploy this correctly?
my pakage.json in the backend is
"client-install": "npm install --prefix myprofile",
"start":"node server.js",
"server":"nodemon server.js",
"client":"npm start --prefix myprofile",
"dev":"concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild":"NPM_CONFIG_PRODUCTION=false npm install --prefix myprofile && npm run build --prefix myprofile"
}
And my server.js is
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const path = require("path");
require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json());
app.use(cors());
//app.use(express.static(path.join(__dirname,'./myprofile/build')));
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB data connected");
});
const CommentRouter = require("./CommentRouter");
app.use("/comment", CommentRouter);
if (process.env.NODE_ENV === "production") {
app.use(express.static("myprofile/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "myprofile", "build", "index.html"));
});
}
app.listen(port, () => console.log(`Server is running on ${port}`));
Thank you very much in advance!
If you are deploying this project to heroku, your start command and your server.js looks similar to this example so that's a good start.
Are you setting your environment variables with heroku, specifically process.env.ATLAS_URI? I would imagine heroku doesn't know where your MongoDB database is located.

How to run an Angular app on a Node server?

I would like to run my app with express on a Node server.
My server.js file:
var express = require('express');
var path = require('path');
var app = express();
app.get('/', (req, res) => {
res.sendFile(path.resolve('dist/my-app/index.html'))
});
app.listen(80, () => {
console.log('Server started!')
})
But when I'm trying to view my website on localhost nothing appears. Can you help me?
Hope this would help you.
1) Run:
ng build --prod
This will create a dist folder. Used for production.
2) Run:
npm install --save express
To install express and save it as dependency in the project.
3) Create a file in root: ./server.js
4) Copy this code. Don't forget to modify with your name project
const express = require('express');
const http = require('http');
const path = require('path');
const app = express();
const port = process.env.PORT || 3001;
app.use(express.static(__dirname + '/dist/my-app-name'));
app.get('/*', (req, res) => res.sendFile(path.join(__dirname)));
const server = http.createServer(app);
server.listen(port, () => console.log(`App running on: http://localhost:${port}`));
5) To run the server.js file
node server.js
I found a solution !
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const port = process.env.NODE_PORT || 3000;
const root = path.join(__dirname, 'dist', 'my-app');
app.get('*' ,function(req, res) {
fs.stat(root + req.path, function(err){
if(err){
res.sendFile("index.html", { root });
}else{
res.sendFile(req.path, { root });
}
})
});
app.listen(port);
console.log('Listening on port '+ port);
You can do this in just very few steps...
1). Run ng build --prod (If you get budgets error than increase the budget in angular.json file according to the error)
2). After above command, a dist folder will be generated containing your project folder, move this project folder which is present inside dist folder from angular project in to your node project say inside public folder (public/your_build_angular_project).
3). Now in your node main file say index.js or app.js, include these lines
const path = require('path');
app.use('/', express.static(path.join(__dirname, 'public/your_build_angular_project')));
4). Now serve your node server then when you hit it, you will get your angular project running
Hope this will help you or somebody else! Thanks.
Sample angularjs app directory is here :
AngularApp->myApp->
AngularApp->myApp->controllers
AngularApp->myApp->views
AngularApp->myApp->services
AngularApp->myApp->app.js
AngularApp->myApp->index.html
Create a package.json file and insert below code in it:
(Location : AngularApp->package.json)
{
"name": "myApp",
"version": "0.0.1",
"description": "My Project",
"dependencies": {
"express": "*"
},
"engine": "node >=0.6.x",
"scripts": {
"start": "node server.js"
},
"main": "server.js",
"repository": {
"type": "git",
"url": ""
},
"author": "myApp",
"license": "myApp",
"bugs": {
"url": ""
},
"homepage": "/"
}
Create server.js:
(Location: AngularApp->server.js )
var express = require('express');
var app = express();
app.use(express.static("myApp")); // myApp will be the same folder name.
app.get('/', function (req, res,next) {
res.redirect('/');
});
app.listen(8080, 'localhost');
console.log("MyProject Server is Listening on port 8080");
Run commnad 'npm install' after navigating to package.json file.
Run command 'npm start'. Open a browser and hit localhost:8080/

Resources