Node.JS will not release localhost - javascript

I was building another application in node locally and have now deployed it and am working on another application.
EDIT
However whenever I start node (v5) with express(v4.13) on my localhost it will just hang and not make any connections I am also on a Mac running El Capitan. All that I ever see in the console (By Console I mean the Terminal via Logging) is:
GET / -- ms --
Here is my code below for guidance.
var express = require('express');
var fs = require('fs');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParer = require('body-parser');
var path = require('path');
var app = express();
var settings = app.settings;
var env = process.env;
var entrance = require('./route/siteBase');
app.set('view engine', 'jade');
app.set('view cache', false);
app.set('views', __dirname + '/source');
app.set('/assets', express.static(__dirname + '/source/assets/'));
app.use(logger('dev'));
app.use(cookieParser);
app.get('/', function (req, res) {
res.send('Hello World!');
});
/**
* 404 Error Handler
* Creates an error object to be used and passed to pages.
* TODO move this out of the server.js
* TODO create generic 500/404 page
* NOTE this must always be the last route called (i.e. if the server cannot find any other routes this will be called)
*/
app.use(function(err, req, res, next){
// error page
res.status(500).render('error', {error : err});
});
app.use(function(req, res, next) {
// logic - TODO: Create Error handling here
// console.log(req);
res.status(404).render('error', { error: req.originalUrl });
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
module.exports = app;
please help!

Ok so after a few more hours of debugging the trace led back to some bad NPM package installs which were somehow causing the issue.
I am still not entirely sure what happened, but basically just had to start over from a fresh project and rebuild.
Thank you for the assistance.

The following things you have to keep in your mind.
install dependencies:
$ cd your_app_name && npm install
Install supervisor and use it:
npm install supervisor -g
Edit package.json file and replace below lines :
"scripts": {
"start": "supervisor ./bin/www"
},
run the app with debug mode:
$ DEBUG=your_app_name:* npm start
run app on different port with debug mode:
$ PORT=8080 DEBUG=your_app_name:* npm start
check port is already running or not:
$ netstat -anp tcp | grep 3000
$ sudo netstat -lpn |grep :3000
Kill the running port:
$ sudo fuser -k 3000/tcp
Convert HTML to Jade: here
http://html2jade.aaron-powell.com/
I hope with above information you can sort out your problem.

In express the ordering matters
You have the hello world route after the error and 404 handler.
You need to reorder them.
// even better create a routes file and include it here
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.use(function(req, res, next) {
res.status(404);
res.send('404: Page not found');
});
app.use(function(err, req, res, next){
res.status(500);
res.send('500');
});
Take a look at a express-boilerplate for more details on including routes

Related

I can’t serve subroutes when I reload the page

It’s the first time I deployed a full-stack app I created on Render and all seems to be working fine except for the fact that my routes are not found when I reload the component. I’ve got a general idea why as I did a research online but I haven’t managed to solve the problem yet.
Here’s my server file
const express = require("express");
const dotenv = require("dotenv");
const connectDB = require("./config/db");
const path = require("path");
const cors = require("cors");
const corsOptions = {
origin: "*",
credentials: true,
optionSuccessStatus: 200,
};
const app = express();
app.use(cors(corsOptions));
// read variables and save them as environment variables
dotenv.config({path: "./.env"});
// Init Middleware
app.use(express.json({extended: false}));
// data from req object is added to it(middleware)
app.use(express.json());
// Define Routes
app.use("/api/data", require("./routes/data"));
app.use("/api", require("./routes/collection"));
app.use(`/api/item`, require("./routes/item"));
app.use(`/api`, require("./routes/under"));
app.use("/api/users", require("./routes/users"));
app.use("/api/auth", require("./routes/auth"));
app.use("/api/email", require("./routes/email"));
app.use("/api/basket", require("./routes/basket"));
app.use("/api/size", require("./routes/size"));
app.use("/api/wishlist", require("./routes/wishlist"));
app.use("/api/checkout", require("./routes/checkout"));
app.use("/api/payment_confirmation", require("./routes/confirmation"));
const PORT = process.env.PORT || 5000;
// Connect to Database
connectDB();
// Load React App in production
if (process.env.MODE === "production") {
app.use(express.static(path.join(__dirname, "build")));
app.get("*", (req, res) => res.sendFile(path.resolve(__dirname, "build", "index.html")));
} else {
app.get("/", (req, res) => {
res.send("Welcome to the home page");
});
}
app.listen(PORT, () => {
console.log(`App running on port ${PORT}`);
});
That's my package.json and my scripts
“scripts”: {
“start”: “node app.js”,
“server”: “nodemon app.js”,
“client”: “npm start --prefix …/client”,
“client:install”: “npm install --prefix client”,
“build”: “npm install --prefix client && npm run build --prefix client”,
"dev": "concurrently \"npm run server\" \"npm run client\""
}
That's my repo if you want to have a look at the file structure.
enter link description here
enter link description here
I get this error on the console
Error: ENOENT: no such file or directory, stat '/opt/render/project/client/build/index.html'
Although on the events log it says that build is successful so I'm not sure what the correct folder would be.
Thanks in advance
When I downloaded the app and ran it on my system reloading the page, it seems like the server cannot find the routes defined in your server file. This is because your server is configured to handle all routes in your React app's index.html file.
your client-side routes will match the routes defined in your React app, and the server will only serve the index.html file for the initial request.
In your server file, modify your app.get("*")method to serve the index.html file only for the initial request:
if (process.env.MODE === "production") {
app.use(express.static(path.join(__dirname, "build")));
app.get("*", (req, res) => {
// Serve index.html for the initial request
if (req.originalUrl === '/') {
res.sendFile(path.resolve(__dirname, "build", "index.html"));
} else {
// Serve static files for all other requests
res.sendFile(path.join(__dirname, "build", req.originalUrl));
}
});
}

Express.js routes do not work in docker container

When I run my Express.js application with node app.js everything works as expected, including this example route:
router.get('/config/get', function(req, res, next) {
return res.json("hi");
});
However, when I build my docker image and run it, my browsers shows me my index page on this route. In fact, it shows my index page at pretty much every single route, nomatter if I set it up or not. So when I go to /this/route/is/non-existing/ I see my index page as well. This only works through docker. When I visit this page by running the node application without docker, I get a 404.
Be aware that I use connect-history-api-fallback for my vue.js frontend. My app.js looks like this:
require('dotenv').config()
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var history = require('connect-history-api-fallback');
var app = express();
// history mode for making vue.js router work: https://router.vuejs.org/guide/essentials/history-mode.html
app.use(history());
history({
index: '/dist/index.html'
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', indexRouter);
// serving vue.js prod build
app.use(express.static('dist'));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
app.listen(process.env.PORT, () => console.log(`${process.env.NAME} listening on port ${process.env.PORT}!`))
This is my Dockerfile:
FROM node:10
# Create app directory
WORKDIR /usr/src/app
# use non-root user to run commands and give him chown permissions for the directory
USER node
COPY --chown=node:node ./backend .
EXPOSE 8080
CMD [ "node", "app.js" ]

Error :Enoent :no such file or directory ,stat 'D:\awesome-testindex.html'

I have a folder named awesome test and it contains index.hml ,node modules and server.js .Here is the server.js file and i am getting this error .
//grab express
var express=require('express');
//create an express App
var app=express();
// create an express route for the home page
// http://localhost:8080/
app.get('/', function(req, res) {
res.sendFile(__dirname + 'index.html');
});
// start the server on port 8080
app.listen(8080);
// send a message
console.log('Server has started!');
Here's where the error is:
res.sendFile(__dirname + 'index.html');
It should be:
res.sendFile(__dirname + '/index.html');
The reason for this is because the index.html is being added upon the directory, which doesn't end with a / by default. You need to add it yourself as shown above.
Hope this helps!
Edit: I tried Node.js before. I think it would be best if you added a "public" folder, with the .js file being above everything. Here's an example:
This was my code for my first Node.js server, as a reference:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const express = require('express');
const app = new express();
app.use(express.static(__dirname + '/public'));
app.listen(3000, () => console.log("Example app listening on port 3000!"))
console.log("http://"+hostname+":"+port)
Note: To use express as shown above, you'll have to open a command line, and type in the following (assuming you have node.js installed correctly):
npm install -g express
Also, to make sure you installed both node.js, do the following:
Node: node -v
Hope everything helps! ^_^

Questions on to use Node.js as local server with Braintree?

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

cannot set node and express to serve files

I use Windows 7. I installed nodes 0.10.12 and latest version of express and express-generator both globally. I
created a new express project named nodetest1 and installed all dependencies succesfully using npm install.
Going to http://localhost:3000/ renders Express Welcome to Express -so it works.
I try to use node and express as simple server now, just use some html files.
According to the book "Jump Start Node.js" by Don Nguyen Copyright © 2012 SitePoint Pty. Ltd. [pages 9-11] , I edited my
app.js file and added
var fs = require('fs');
and after
var routes = require('./routes/index');
var users = require('./routes/users');
I added
app.get('/form', function(req, res) {
fs.readFile('./form.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
});
Then I created a simple form.html file put it in the nodetest1 directory, restarted my server and in the command line I get
app.get('/form', function(req, res) {
TypeError : Cannot call method 'get' of undefined
npm ERR! weird error 8
npm ERR! not ok code 0
What am I doing wrong? I just want to use simple html, not Jade.
Also do I have to edit the app.js for every html file I add? And where will I add the new files, in what folder?
Thanks in advance
Did you create the express app?
var express = require('express');
var app = express();
Also, you can just use res.sendFile for this.
app.get('/form', function(req, res) {
return res.sendFile('form.html');
});
If you are serving up a lot of static files you may want to look into express.static middleware.
http://expressjs.com/4x/api.html#app.use
This will serve up all files you put in your public directory:
app.use(express.static(__dirname + '/public'));
Directory structure:
|-app.js
|-public
| |-index.html
| |-form.html
You're form.html will be served to localhost:3000/form.html
If you wan't to serve up html files without an extension you can use the solution found in this other answer to a different question by #robertklep.
Any way to serve static html files from express without the extension?
app.use(function(req, res, next) {
if (req.path.indexOf('.') === -1) {
var file = publicdir + req.path + '.html';
fs.exists(file, function(exists) {
if (exists)
req.url += '.html';
next();
});
} else {
next();
}
});
You'll want this to be before app.use(express.static(__dirname + 'public'));
Note: The book you mentioned was published Dec 2, 2012. Express 3 was released Oct 23, 2013 according to github. The current version is 4.8.5. You may want to use a more current reference.

Categories