I have tried to install the NPM packages from the cpanel. But when I try to open the website, I get the response incomplete response received from application. When i run it offline, it works properly, but when i move it to the cpanel, it gives me the incomplete response error
var express = require("express"),
app = express(),
mongoose = require("mongoose"),
flash = require("connect-flash"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
session = require("express-session"),
methodOverride = require("method-override"),
nodemailer = require("nodemailer"),
multer = require("multer"),
dotenv = require("dotenv").config(),
Product = require("./models/products"),
User = require("./models/user");
var mongoDB = process.env.MONGODB_URL;
mongoose.connect(mongoDB, { useNewUrlParser: true , useUnifiedTopology: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
var indexRoutes = require("./routes/index"),
storeRoutes = require("./routes/products");
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use(flash());
//User Passport Config
app.use(require("express-session")({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.error = req.flash("error");
res.locals.success = req.flash("success");
next();
});
app.use(indexRoutes);
app.use("/store", storeRoutes);
app.use(function(req, res){
res.send ("Error finding page")
})
const port = process.env.PORT;
app.listen (port, function(){
console.log ("Server Active");
});
this is what i saw in the the .htaccess file. I only placed some passwords and other private info in the .env file
# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php70” package as the default “PHP” programming language.
<IfModule mime_module>
AddHandler application/x-httpd-ea-php70 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN
PassengerAppRoot "/home/zenitcou/zenitcouture"
PassengerBaseURI "/"
PassengerNodejs "/home/zenitcou/nodevenv/zenitcouture/11/bin/node"
PassengerAppType node
PassengerStartupFile app.js
# DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN
<IfModule Litespeed>
</IfModule>
# DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION END
Share the response you are getting, that we can help you better
From the configuration provided, I can't tell the exact cause but I may have enough experience why you end up getting "incomplete response received from the application".
The error message might be confusing, but what it really wants to say is, nothing is actually sent from your app upon HTTP request is sent by the proxy aka. Phusion Passenger.
You can read more about what are those Passenger config in their docs
but my gist is one of these:
Your app is maybe crashed due to improper configuration. I suggest using PassengerAppEnv development to track error messages.
Phusion passenger integration on Node.JS is somewhat magic, they just don't care what app.listen port you're giving on. But it probably crashes because you set them undefined. Please set a fallback on your PORT env like const port = process.env.PORT || 80;
You set PassengerStartupFile as app.js. Is it true? (People usually set their main entry file as server.js. You have to make sure the file exists.
I faced the same error.
For me, it was log4js. The process.send() function was undefined.
By disabling the clustering of log4js, all become fine.
To find where the error is, I proceeded with code reduction. Compiling a few lines of codes
May it helps someone
Related
Could you help me solve this error? It seems that I can not connect between server.js and app.js.
What I want to do is: display the result of the postData('/add', {answer:42}); and postData('/addMovie', {movie:'the matrix', score:5}); in the console.
Thank you for your help in advance.
error image
server.js
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');//add
// Start up an instance of app
const app = express();//add
/* Dependencies */
const bodyParser = require('body-parser') //add
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
//we can connect the other packages we have installed on the command line to our app in our code with the .use() method
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');//add
app.use(cors());//add
// Initialize the main project folder
app.use(express.static('website'));
////////////////////creating a local server
const port = 5500;//add
// Setup Server
//////////////////////add
const server = app.listen(port, listening);
function listening(){
// console.log(server);
console.log(`running on localhost: ${port}`);
};
app.get('/all', function (req, res) {
res.send(projectData)
})
// POST route
const data = []
app.post('/add', callBack);
function callBack(req,res){
res.send('POST received');
console.log(data)
}
const movieData = []
app.post('/addMovie', addMovie )
function addMovie (req, res){
movieData.push(req.body)
console.log(movieData);
}
app.js
app.js
[Addition]
Thank you for your feedback!!
I changed the port in server.js, but nothing changed.
port5500
The issue was resolved.
// when using local server ( ≒ server.js in this case)
postData('/add', {answer:42});
postData('/addMovie', {movie:'the matrix', score:5});
// when using live server
postData('http://localhost:5500/add', {answer:42});
postData('http://localhost:5500/addMovie', {movie:'the matrix', score:5});
You need to add an "allow" in the header field to support this or explicitly allow it in your webserver configuration
A lot of the time, this is set up in the configuration of your .htaccess or nginx.conf file (depending on the webserver). It will commonly be found in your RewriteRule section. You can look for a "R=405" flag there.
I am following a tutorial (https://levelup.gitconnected.com/simple-application-with-angular-6-node-js-express-2873304fff0f) on creating an app with Angula CLI, Node.js and Express. I use a proxy to start the app, the file defining the proxy looks like this:
{
"/api/*": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
The command I use to start the app is this one:
ng serve --proxy-config proxy.conf.json
The tutorial said that:
All requests made to /api/... from within our application will be forwarded to http://localhost:3000/api/...
To be honest, I don't really know how it is supposed to work, because when I launch the app, I still use the URL: http://localhost:4200/ .
But I didn't have a problem until now. I just created a route with Express.js at the Endpoint /api/v1/generate_uid .
But the problem is when I go to http://localhost:4200/api/v1/generate_uid it shows this message:
Error occured while trying to proxy to: localhost:4200/api/v1/generate_uid .
The following is the message I get in the console:
[HPM] Error occurred while trying to proxy request /api/v1/generate_uid from localhost:4200 to http://localhost:3000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
And when I go to http://localhost:3000 it always says that the connection has failed.
For further references, Here are the app.js of my express API and generate_uid.js which defines the route:
app.js
var express = require('express');
var uid = require('uid-safe');
var router = express.Router();
router.get('/', function(req, res, next) {
var strUid = uid.sync(18);
res.json({guid: strUid});
});
module.exports = router;
generate_uid.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var users = require('./routes/users');
var generate_uid = require('./routes/generate_uid');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser())
app.use('/api/v1/users', users);
app.use('/api/v1/generate_uid', generate_uid);
module.exports = app;
So I really don't know what the solution is. Thanks in advance for your answers !!
As said in the comments, it looks like the app doesn't have the .listen() function, which is very important to bind to the port.
app.listen(3000, () => {
console.log("Server started in port 3000!");
});
I'm not new to JavaScript but I am new to Node.js and back end languages. I have a very simple question.
I've installed and setup Node.js on my computer and I'm attempting to get a server going between my static files & directory(s) and my browser to be able to send and receive requests. I've downloaded Braintree's free Sandbox (found here) for practice to get some faux transactions going just to gain a better understanding of how this can work.
I set up a local server by running npm install -g http-server on my command line and then http-server to set it up.
I then received the following message in my command line:
Starting up http-server, serving ./public
Available on:
http://127.0.0.1:8080
http://10.0.1.4:8080
Hit CTRL-C to stop the server
So, with this setup...if I wanted to do get() and post() methods and see it rendered and communicating between my "server" and my static files. How do I do this? For example, if I were to set up Braintree's sandboxed environment and then create a clientToken using the following code from Braintree's website
const http = require('http'),
url = require('url'),
fs = require('fs'),
express = require('express'),
braintree = require('braintree');
const gateway = braintree.connect({
environment: braintree.Environment.Sandbox,
merchantId: "xxxxx",
publicKey: "xxxxx",
privateKey: "xxxxx" //blocked out real numbers for privacy
});
Here is the remaining code I hae to create a "client Token" for a transaction...and here is the guide I'm following via Braintree's website...
http.createServer((req,res) => {
gateway.clientToken.generate({
},(err, response) => {
if(err){
throw new Error(err);
}
if(response.success){
var clientToken = response.clientToken
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(clientToken);
res.end("<p>This is the end</p>");
} else {
res.writeHead(500, {'Content-Type': 'text/html'});
res.end('Whoops! Something went wrong.');
}
});
}).listen(8080,'127.0.0.1');
So, my question is...if I wanted to generate send a token to a client using the get() method...how would I do that? Would it have to be a separate js file? How would they be linked? If they're in the same directory will they just see each other?
Here is an example on Braintree's website of how a client token may be sent:
app.get("/client_token", function (req, res) {
gateway.clientToken.generate({}, function (err, response) {
res.send(response.clientToken);
});
});
How could this be integrated into my current code and actually work? I apologize if these are elementary questions, but I would like to gain a better understanding of this. Thanks a lot in advance!
I don't know much about braintree, but usually you would use somthing like express.js to handel stuff like this. So I'll give you some quick examples from an app I have.
#!/usr/bin/env node
var http = require('http');
var app = require('../server.js');
var models = require("../models");
models.sync(function () {
var server = http.createServer(app);
server.listen(4242, function(){
console.log(4242);
});
});
So that's the file that gets everything started. Don't worry about models, its just syncing the db.
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
// share public folder
app.use(express.static(path.join(__dirname, 'public')));
require('./router.js')(app);
module.exports = app;
next up is the server.js that ties eveything together. app.use() lines are for adding middleware and the app.use(logger('dev')); sets the route logger for what your looking for.
app.use(express.static(path.join(__dirname, 'public'))); shares out all files in the public directory and is what your looking for for static files
var path = require('path');
module.exports = function(app){
//catch
app.get('*', function(req, res){
res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});
}
last piece is the router.js. This is were you would put all of you get and post routes. generally I've found that if you see app.get or app.post in examples there talking about express stuff. It's used a lot with node and just makes routing way easier.
Also if your using tokens a route would look like this.
app.get('/print', checkToken, function(req, res){
print.getPrinters(function(err, result){
response(err, result, req, res);
});
});
function checkToken(req, res, next){
models.Tokens.findOne({value: req.headers.token}, function(err, result){
if(err){
res.status(500).send(err);
}else if(result == null){
console.log(req.headers);
res.status(401).send('unauthorized');
}else{
next();
}
});
}
so any route you want to make sure had a token you would just pass that function into it. again models is for db
I am building a REST API using NodeJS and Express, powered by a MongoDB database.
I've been struggling for days now trying to get the right folder structure nailed down. So far, I can connect to my database and add new users without an API, but by simply doing GET, POST, etc. requests. I've seen several tutorials online on how to build API using node, but none of them have a more standardized way for setting their folder structure. And that is the reason why I am having such a hard time making it work given my current folder structure.
Here is my Folder Structure
app
---models
------user.js
---api.js
---routes.js
config
---auth.js
---database.js
---passport.js
public
views
package.json
server.js
Server.js
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 2016;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
app.configure(function() {
// set up our express application
app.use(express.logger('dev')); // log every request to the console
app.use(express.cookieParser()); // read cookies (needed for auth)
app.use(express.bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.set('views', path.join(__dirname + '/views'));
app.set('view engine', 'ejs'); // set up ejs for templating
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// required for passport
app.use(express.session({ secret: 'xxxxxxxxx' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
});
// routes ======================================================================
// require('./app/routes')(app, passport); // load our routes and pass in our app and fully configured passport
// require('./app/api')(api, passport);
app.use('/', require('./app/routes')(app, passport));
app.use('/api', require('./app/api')(api, passport));
// error handlers
// Catch unauthorised errors
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
res.status(401);
res.json({"message" : err.name + ": " + err.message});
}
next();
});
// launch ======================================================================
app.listen(port);
console.log('Live on port ' + port);
api.js
var User = require('./models/user');
var express = require('express');
var apiRoutes = express.Router();
app.use('/api', apiRoutes);
module.exports = function(apiRoutes, passport){
apiRoutes.get('/testapi', function (req,res) {
res.json({SecretData: 'abc123'});
});
}
Every time I hit the endpoint /testapi I get the error "Cannot GET /testapi"
I think my main issue is how to organize my files and folder properly and import/require them the right way. Can anyone help me figure this out?
Server.js
on this line app.use('/api', require('./app/api')(api, passport));
Here you are telling Express to use ./app/api as an middleware by passing "api" and "passport" as arguments.
where you have defined api variable ?
Lets assume its a typo.. in that case from "app/api.js" you are exporting a function and you trying to execute it in server.js app.use('/api', require('./app/api')(api, passport)); which returns undefined.
Express will be expecting a function as middleware not a return value from function.
app/api.js
on line 4 you have app.use('/api', apiRoutes); which doesn't make any sense, because api.js has no idea about "app".
Cleanup your server.js and api.js and try again
This tutorial might help Node with Express
form.parse() never called, when i delete bodyparser then it, my session variable throughs error , how to make it work
logcat
write(string, encoding, offset, length) is deprecated. Use
write(string[, offset[, length]][, encoding]) instead. events.js:85
throw er; // Unhandled 'error' event ^ Error: ENOENT, open
'/home/pitu/CODING/NODE-PROJECTS/chichat/files/a88b7a4fbd8cb31e276ef60c8e934d2d.png'
at Error (native)
app.js file
var express = require('express'),
app = express(),
http = require('http'),
path = require('path'),
fs = require('fs'),
mysql = require('mysql'),
server = http.createServer(app),
//events = require('events'),
//path = require('path'),
//url = require('url'),
//Create a new store in memory for the Express sessions
sessionStore = new express.session.MemoryStore(),
passport = require('passport'),
flash = require('connect-flash'),
useragent = require('express-useragent'),
cookieParser = express.cookieParser('hjnjnm'),
io = require('socket.io').listen(server);
// configuration ===============================================================
// connect to our database
require('./config/passport')(passport); // pass passport for configuration
app.configure(function() {
// set up our express application
app.use(express.logger('dev')); // log every request to the console
app.use(cookieParser); // read cookies (needed for auth)
app.use(useragent.express());
app.use(express.methodOverride());
app.use(express.bodyParser({keepExtensions:true,uploadDir:path.join(__dirname,'/files')}));
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(express.session({store: sessionStore,key: 'myuser.sid',cookie: { secure: false,maxAge:3600000}} )); // session secret1
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(path.join(__dirname, 'public')));
app.all('*', function(req, res, next)
{
res.header("Access-Control-Allow-Origin", "*");
res.set('Access-Control-Allow-Methods', 'GET, POST');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
});
require('./app/socket/mainSocket.js')(app,io,sessionStore,cookieParser);
// routes ======================================================================
require('./app/controller.js')(app, passport,io); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
server.listen(8080);
what should i use, bodyparser or formidable, i want to upload big file to server, which one will suit my need with minimum overhead.
any help will be appreciated, thank you
[1]: https://stackoverflow.com/a/25016730/2254638 it solved my issue,happy coding , :)