Home > Mobile >  How to deploy Node JS app cPanel from localhost to a server
How to deploy Node JS app cPanel from localhost to a server

Time:01-15

I have created a simple Express JS app. and it is working fine in localhost. when I visit localhost:8000 I see static files (index.html, style.css and frontend.js).

I have tried to deploy that app in a server using cPanel. and I have installed Node app and dependencies using package.json successfully. But when I visit the domain I just see a message (Node JS app is working, Node version is 10.24.1).

How to make my app to point and display the static folder (index.html) and run the app?

My app architecture:

  • server.js
  • package.json
  • public/index.html
  • public/style.css
  • public/frontend.js

And here is my server.js startup file:

// Setup empty JS object to act as endpoint for all routes
projectData = {};

// Require Express to run server and routes
const express = require('express');

// Start up an instance of app
const app = express();

/* Dependencies */
const bodyParser = require('body-parser');

/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());

// Initialize the main project folder
app.use(express.static('public'));


// Setup Server
const port = 8000;

const server = app.listen(port, function(){
    console.log(`server running on localhost: ${port}`);
});


//POST Route to store data in the app endpoint, projectData object
app.post('/addData', addData);


function addData (req, res){
   let data = req.body;
   projectData = data;
   console.log(projectData);
}

app.get('/getData', getData);

function getData(req, res) {
  res.send(projectData);
}

CodePudding user response:

The problem here is that you are not pointing a route to send the HTML file. Otherwise the client would have to point it to the correct path of the file, Like localhost:3000/index.html. you need to send it from the server using app.get

app.get("/", (req, res) => {
  res.sendFile(__dirname   "path to the file");
});

CodePudding user response:

The problem was that I have created the app in a subfolder of my domain. But when I have created subdomain and reinstalled the app inside it, the app is pointing to static folder successfully.

  •  Tags:  
  • Related