starting a next server on cpanel throwing 503 service unavailable - javascript

I'm attempting to deploy a NextJS app on my shared hosting server using the cPanel Setup Node.JS App section, but when I start the build - despite getting ready on http://localhost:3000 - the site throws a 503 error.
I've uploaded the build folder alongside the next.config.js, package-lock.json, package.json and server.js to the application root, and this is my current file structure:
next_main
build (.next folder)
node_modules
next.config.js
package-lock.json
package.json
server.js
This is my server.js file (exactly the same as what Next provided in their custom server docs):
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 3000;
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer(async (request, response) => {
try{
const parsedURL = parse(request.url, true);
const { pathname, query } = parsedURL;
switch(pathname){
case "/a":
case "/b":
await app.render(request, response, pathname, query);
break;
default:
await handle(request, response, parsedURL);
}
} catch(error){
console.error("Error occurred.", request.url, error);
response.statusCode = 500;
response.end("Internal server error.");
}
}).listen(port, error => {
if(error) throw error;
console.log(`> Ready on http://${hostname}:${port}`);
});
}).catch(error => {
if(error) throw error;
});
Failed to load next.config.js was also output in my stderr file, despite next.config.js being provided.
I've attached the current settings I have applied in my cPanel.
Please note that I do not have root access to the terminal, and am restricted to the next_main environment when running any NPM scripts.

Make sure you add all environmental variables in the .env file. add your variable here

Related

Displaying my own CSV Data with my own model, Forge autodesk

I hope you all are well. I am having trouble with displaying my own forge data in the AutoDesk Forge reference application. My current .env file is as follows. However, whenever I launch it in http://localhost:9000/upload all I get in return is a blank empty screen.
FORGE_CLIENT_ID=STEHw2Qx... marked ...xrIJUeKRj6 #changed for post
FORGE_CLIENT_SECRET=A54... marked ...c348a #changed for post
FORGE_ENV=AutodeskProduction
FORGE_API_URL=https://developer.api.autodesk.com
FORGE_CALLBACK_URL=http://localhost:9000/oauth/callback
FORGE_BUCKET=cosmostool1.cosmosengineering.es #changed for post
ENV=local
#ADAPTER_TYPE=local
## Connect to Azure IoTHub and Time Series Insights
# ADAPTER_TYPE=azure
# AZURE_IOT_HUB_CONNECTION_STRING=
# AZURE_TSI_ENV=
#
## Azure Service Principle
# AZURE_CLIENT_ID=
# AZURE_APPLICATION_SECRET=
#
## Path to Device Model configuration File
# DEVICE_MODEL_JSON=
## End - Connect to Azure IoTHub and Time Series Insights
ADAPTER_TYPE=csv
CSV_MODEL_JSON=server/gateways/synthetic-data/device-models.json
CSV_DEVICE_JSON=server/gateways/synthetic-data/devices.json
CSV_DATA_END=2011-02-20T13:51:10.511Z #Format: YYYY-MM-DDTHH:MM:SS.000Z
CSV_DELIMITER="\t"
CSV_LINE_BREAK="\n"
CSV_TIMESTAMP_COLUMN="time"
if (process.env.ENV == "local") {
require("dotenv").config({
path: __dirname + "/../.env",
});
}
Because of this line at forge-dataviz-iot-reference-app/server/router/Index.js#L25, you must specify ENV=local before executing npm run dev. Otherwise, it won't read the content of .env.
if (process.env.ENV == "local") {
require("dotenv").config({
path: __dirname + "/../.env",
});
}
Or you can just change it to the below
require("dotenv").config({
path: __dirname + "/../.env",
});
Install dotenv
npm install dotenv
Create a config.js file in your directory and add the following code;
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
// Set environment variables or hard-code here
azure: {
azure_conn_string: process.env.AZURE_IOT_HUB_EVENT_HUB_CONNECTION_STRING
}
};
Update your localserver.js file
const { app, router } = require("./app.js");
const config = require('./config');
app.use(router);
const server = require("http").createServer(app);
if (config.azure.azure_conn_string) {
require("./RealTimeApi.js").createSocketIOServer(server);
}
const PORT = process.env.PORT || 9000;
async function start() {
try { server.listen(PORT, () => { console.log(`localhost: ${PORT}`); }); } catch (error) { console.log(error); }
} start();

ERR_MODULE_NOT_FOUND: Cannot find Module Error

Problem Summary
I am working on the backend of a MERN stack app that pulls restaurant data from a mongo collection. When I run nodemon server inside of the backend folder, I obtain the error ERR_MODULE_NOT_FOUND:
[nodemon] 2.0.16
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server index.js`
node:internal/errors:466
ErrorCaptureStackTrace(err);
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '[redacted]/backend/dao/restaurants.DAO' imported from [redacted]/backend/api/restaurants.controller.js
at new NodeError (node:internal/errors:377:5)
at finalizeResolution (node:internal/modules/esm/resolve:405:11)
at moduleResolve (node:internal/modules/esm/resolve:966:10)
at defaultResolve (node:internal/modules/esm/resolve:1174:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:605:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:318:18)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:80:40)
at link (node:internal/modules/esm/module_job:78:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
Node.js v18.2.0
[nodemon] app crashed - waiting for file changes before starting...
Problem Details
My Folder Structure
My folder structure looks like this
restaurant.route.js
import express from "express";
import RestaurantsCtrl from "./restaurants.controller.js";
// create router instance
const router = express.Router();
// respond to GET requests with hello
router.route("/").get(RestaurantsCtrl.apiGetRestaurants);
export default router;
restaurants.controller.js
import RestaurantsDAO from "../dao/restaurants.DAO";
export default class RestaurantsCtrl {
static async apiGetRestaurants(req, res, next) {
// if there is a number of restaurants to show per page passed in the URL, conver it to an integer. Otherwise set it to 20
const restaurantsPerPage = req.query.restaurantsPerPage ? parseInt(req.query.restaurantsPerPage, 10) : 20;
// if there is a page number passed in the URL, conver it to an integer. Otherwise set it to 0
const page = req.query.page ? parseInt(req.query.page, 10) : 0;
let filters = {};
// if we see filters passed in the URL, add it to the filters
if (req.query.cuisin) {
filters["cuisine"] = req.query.cuisine;
}
else if (req.query.zipcode) {
filters["zipcode"] = req.query.zipcode;
}
else if (req.query.name) {
filters["name"] = req.query.name;
}
// get the list of restaurants and a number of restaurants from the database
const { restaurantsList, totalNumRestaurants } = await RestaurantsDAO.getRestaurants({
filters,
page,
restaurantsPerPage,
});
// create a response object to send back to the client
let response = {
restaurants: restaurantsList,
page: page,
filters: filters,
entries_per_page: restaurantsPerPage,
total_results: totalNumRestaurants,
}
// send the response back to the client
res.json(response);
}
}
server.js
import express from "express";
import cors from "cors";
import restaurants from "./api/restaurants.route.js";
// Create a new express application instance
const app = express();
// apply middleware
app.use(cors());
// parse request body as JSON. Our server can accept JSON data in the body of a request
app.use(express.json());
// specify some routes. This is the path that will be used to access the API
app.use("/api/v1/restaurants", restaurants);
// If someone goes to a path that doesn't exist, return a 404 error
app.use("*", (req, res) => res.status(404).json({error : "Not found"}));
// export the application instance for use in the rest of the application
export default app
index.js
import app from "./server.js"
import mongodb from "mongodb";
import dotenv from "dotenv";
import RestaurantsDAO from "./dao/restaurants.DAO.js";
// Load environment variables from .env file, where API keys and passwords are configured
dotenv.config();
// Get access to the mongo client
const MongoClient = mongodb.MongoClient;
// set port
const port = process.env.PORT || 8000;
// Connect to the database
const a = MongoClient.connect(
// The URL of the database to connect to
process.env.RESTREVIEWS_DB_URI,
{
// The options to use when connecting to the database
maxPoolSize: 50,
wtimeoutMS: 2500,
useNewUrlParser: true,
}
)
// If the connection is not successful, throw an error
.catch(err => {
console.log(err.stack);
process.exit(1);
})
// If the connection is successful, console log a message
.then(async client => {
// Get a reference to the database
await RestaurantsDAO.injectDB(client);
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
});
I found the solution to this problem.
I needed to add .js at the end of restaurants.DAO in the line import RestaurantsDAO from "../dao/restaurants.DAO";
of the file restaurants.controller.js

Nodejs fails to show output on the cmd

I'm new to nodejs, All I'm trying to do is running a simple nodejs file on windows console Here's what I'm doing :
const http = require('http');
const host = '127.0.0.1';
const port = 3000;
const server = http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.end('Hello world');
}).listen(port, host);
server.on('connect', function(req) {
console.log(req.url);
console.log('Connected!');
})
server.on('error', function(e) {
console.log(e);
})
The file is stored on D:\nodjs\test directory when I navigate to this directory and run
the node hello.js command I'm expecting to see outputs ( response ) on the console.
However this is not happening, it just show a blank response, I wonder if it takes too long to load or anything else might be related with my client/port setup ?

make nextJS ignore a subPath in host

so the problem i'm having is, there is a directory in my public_html file named blog that is not related to my nextJs app, so basically after i deploy the app on host, everything works fine until i choose to check my blog part, for example the url below:
www.sth.com/blog
when i get there, i get the default next 404 page, the problem is, there is actual pages there, and i want my nodeJs server to ignore that exact route so when user goes to www.sth.com/blog, node app kind of ignore it and let it load the basic html pages.
i think it has something to do with my server.js file so here's the code in server.js
also i hosted the app on cpanel if that's important.
const { createServer } = require('http')
const next = require('next')
const isDevMode = process.env.NODE_ENV !== 'production'
const port = process.env.PORT ? process.env.PORT : 3000
const nextjsApp = next({ dev: isDevMode })
const nextjsRequestHandler = nextjsApp.getRequestHandler()
nextjsApp
.prepare()
.then(() => {
createServer((req, res) => {
const url = new URL(req.url, "http://w.w")
nextjsRequestHandler(req, res, url)
}).listen(port, (err) => {
if (err) throw err
})
})
.catch((ex) => {
console.error(ex.stack)
process.exit(1)
})
thank you in advance.
In your server configuration you have to check if request is meant for next or not. If not - you need to respond with your page, instead of passing request further to next:
(req, res) => {
const url = new URL(req.url, "http://w.w");
if (/^\/blog\//.test(url.pathname)) {
// send response with blog
} else {
// pass everything to Next
nextjsRequestHandler(req, res, url);
}
};
Another option would be to split next and not next in two different parts and route requests to them through reverse proxy.

404 - File or directory not found in Next JS

I am making a next js application.
Deployment works fine in vercel.
For deploying the same project in another server, got help from https://stackoverflow.com/a/63660079/13270726 and used the same instructions in our app.
Deployed the out directory into server using ftp client.
Issue
-> When we enter into http://your-domain.com , it works fine. (Even page refresh also works fine in this page)
-> If we move to about page using the url, http://your-domain.com/about then it also works but on page refresh in the url http://your-domain.com/about results in the error,
-> This page refresh also results in the console error like,
Get http://your-domain.com/about Not found
next.config.js: (With public path)
const config = {
webpack: (config, { isServer }) => {
.
.
.
config.devServer = {
historyApiFallback: true
}
config.output.publicPath = "/"
return config;
}
}
module.exports = withPlugins(config);
The issue arises in page refresh only or when we manually type the url.. But while we navigate to it first time then the issue is not there.
Any good help would be much appreciated as I am stuck for long time..
Edit:
I have a server.js file and its code look like,
const dotenv = require("dotenv");
// import ENVs from ".env.local" and append to process
dotenv.config({ path: ".env.local" });
const express = require("express");
const address = require("address");
const chalk = require("chalk");
// create express web server instance
const app = express();
// pull out ENVs from process
const { LOCALHOST, PORT } = process.env;
// get the Local IP address
const LOCALIP = address.ip();
// tell express to serve up production assets from the out directory
app.use(express.static("out" + '/'));
app.get('/*', (req, res) => {
res.send('ok')
});
app.all('*', function(req, res) {
res.redirect('/index.html');
});
// tell express to listen for incoming connections on the specified PORT
app.listen(PORT, (err) => {
if (!err) {
// log the LOCALHOST and LOCALIP addresses where the app is running
console.log(
`\n${chalk.rgb(7, 54, 66).bgRgb(38, 139, 210)(" I ")} ${chalk.blue(
"Application is running at"
)} ${chalk.rgb(235, 220, 52).bold(LOCALHOST)} ${chalk.blue(
"or"
)} ${chalk.rgb(235, 220, 52).bold(`http://${LOCALIP}:${PORT}`)}\n`
);
} else {
console.err(`\nUnable to start server: ${err}`);
}
});

Categories

Resources