I am trying configure my node js to run my html code.I am using bootstrap and Express Js also.When I run node js its not loading the css.Can anyone help me what could be the issue.Here is the node js code snippet.
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res) {
res.sendFile(__dirname + '/home.html')
})
app.use(express.static(__dirname + '/public'))
app.listen(3000);
console.log("Running at Port 3000");
When I directly load the HTML files it loads the CSS properly but when i use node js to load it it fails.What could be the cause of the issue?
Check your directory structure is correct and that you have given the correct permission for Node.js to enter the directories and read the file.
If your directory structure looks like this:
/public
/stylesheets
home.css
home.html
server.js
And your server.js code looks like this:
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res) {
res.sendFile(__dirname + '/home.html');
})
app.use(express.static(__dirname + '/public'));
app.listen('3000', function() {
console.log("Listening on port 3000");
});
When you run this:
node ./server.js
And visit this URL in your browser:
http://localhost:3000/stylesheets/home.css
You will get your home.css file returned.
In express js project to configuration database
/config
/database.js
/server.js
/.env
const http = require('http');
const app = require('express')();
require('./config/database.js');
const bodyParser = require('body-parser');
const server = http.createServer(app);
server.listen(process.env.ServerPort, '0.0.0.0', () => {
logger.info(`Express server listening on port ${process.env.ServerPort}`);
});
When you run this:
node server.js
database.js file
const My = require('jm-ez-mysql');
// Init DB Connection
const connection = My.init({
host: process.env.DBHOST,
user: process.env.DBUSER,
password: process.env.DBPASSWORD,
database: process.env.DATABASE,
dateStrings: true,
charset: 'utf8mb4',
timezone: 'utc',
multipleStatements: true,
connectTimeout: 100 * 60 * 1000,
acquireTimeout: 100 * 60 * 1000,
timeout: 100 * 60 * 1000,
});
module.exports = {
connection,
};
In express js project, as require you can place you static file.
app.use('/static', express.static('public'))
Now, you can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
https://expressjs.com/en/starter/static-files.html
check this link for how you can connect your static files with express js
Related
const express = require("express");
const app = express();
app.get("/hello", (req, res) => {
res.send("Hello World");
});
app.listen(3000);
I run this simple code in VS code but It isn't showing in localhost 8080 on web browser
I want to know what did happen and How to solve this one ?
I want to show index.html on special page '/chess', not on home page '/'.
Simple
app.get('/chess', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
doesn't work.
I get the below error
To create more of the "game center" try the approach of making realchess a router that gets imported to the main app.js
below is how I was able to achieve the desired result
rename app.js to chess.js
chess.js
var express = require('express');
var app = express();
app.use(express.static('public'));
app.use(express.static('dashboard'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
... rest of code ...
http.listen(port, function() {
console.log('listening on *: ' + port);
});
becomes
module.exports = function(server){
var express = require('express');
var app = express.Router();
app.use(express.static('public'));
app.use(express.static('dashboard'));
var io = require('socket.io')(server);
... rest of code ...
return app;
}
remove lines 145-147 and add module.exports = app;
create a new app.js
const express = require("express");
const app = express();
const http = require('http').Server(app);
const chess = require("./chess")(http);
const port = process.env.PORT || 3000;
app
.get("/", (req, res) => {
res.sendFile(__dirname + "/public/selector.html");
})
.use("/", express.static("public"))
.use("/chess",chess);
http.listen(port, function () {
console.log('listening on *: ' + port);
});
this will mound the chess router on the /chess directory, and allow you to mount a selector.html at /. Following a similar patter you could mount other games
Don't forget to declare the public director using use method.
app.use(express.static(__dirname + '/public'));
Using the code below i was able to remap
route '/chess' to serve index.html,
And
route '/' to serve select.html.
const express = require("express");
const app = express();
app
.get("/", (req, res)=>{
res.sendFile(__dirname + "/public/select.html");
})
.get("/chess", (req, res)=>{
res.sendFile(__dirname + "/public/index.html");
});
app.listen(3000, () => console.log("Example app listening on port 3000!"));
Can you post more of you application to see if there is another problem?
Moved routes into their own folder now I cant parse the response body. Controller sends body correctly. App worked correctly when routes were in server js file.
Server.js BEFORE
var express = require('express');
var app = express();
var routes = require('./routes/routes.js');
app.use('/',routes);
app.use(express.static(__dirname + '/public'));
app.use('/bootstrap', express.static(__dirname + '/public/bower_components/bootstrap/dist'));
app.use('/jquery', express.static(__dirname + '/public/bower_components/jquery/dist'));
app.use('/angular', express.static(__dirname + '/public/bower_components/angular'));
app.use('/controllers', express.static(__dirname + '/public/controllers'));
Routes.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var ObjectId = require('mongojs').ObjectID;
var mongojs = require('mongojs');
var db = mongojs('contactlist',['contactlist'])
var router = express.Router();
app.use(bodyParser.json());
router.put('/contactlist/:id',function(req,res){
console.log("req.body.name");//gives undefined
db.contactlist.findAndModify({
query:{_id: ObjectId(req.params.id)},
update:{ $set:{name:req.body.name,email:req.body.email,number:req.body.number}},
new: true},
function(err,doc){
res.json(doc);
});
});
module.exports = router;
Also, any thoughts as to why I have to append routes.js here instead of just / routes?
var routes = require('./routes/routes.js');
Folder Structure
-App
node_mods/
public/
index.html
controllers/
resources/
routes/
routes.js
Server.js AFTER
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var routes = require('./routes/routes.js');
app.use('/',routes);
app.use(express.static(__dirname + '/public')); //look for static files js html css etc
app.use('/bootstrap', express.static(__dirname + '/public/bower_components/bootstrap/dist'));
app.use('/jquery', express.static(__dirname + '/public/bower_components/jquery/dist'));
app.use('/angular', express.static(__dirname + '/public/bower_components/angular'));
app.use('/controllers', express.static(__dirname + '/public/controllers'));
app.listen(3000);
console.log('server running on port 3000');
As for your (second?) quetion , about importing requiring routes.js:
When you do
var routes = require('./routes/routes.js');
you're not calling the routes. You're, in fact requiring a module. That is not only routes data, but also the router object Behaviour, including associated middleware for some of all of the routes.
If you look carefully, your router.js exports the router "object" ( or function, call it as you want). So when you require it, you get the whole package, not only data
Your body is parsing after your route is called.
Pass your body-parser code in your main server file generally, it is server.js before all the routes.
Like this:
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
I want to deploy my node.js web app on heroku.
My server.js is as follow :
// set variables for environment
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
var pdf = require('express-pdf');
var projectDir = __dirname+'/../..';
app.set('port', (process.env.PORT || 5000));
app.use(express.static(projectDir+'/public'));
app.use(bodyParser.json());
app.use(pdf)
app.use('/pdf', express.static(projectDir + '/data/json/output.pdf'));
app.use('/json', express.static(projectDir+'/data/json'));
require('./saveLastConf')(app, projectDir+'/data/json')
// Set server port
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
console.log('server is running');
My code is working locally but when i try heroku local web or when i deploy it on the website my files under data/json/test.json cannot be found (404)
(i call my file like that : https://a.com/json/test.json )
can anyone help me solve this ?
thank you.
I have an app hosted in appfog using node-express and mysql( and backbone js in the client side), it works fine in localhost but when deploy the app works fine for a moment and after a time crash( if i restart in the console of appfog admin the same thing happens)
this is part of code for connection mysql
var mysql = require("mysql")
var env = JSON.parse(process.env.VCAP_SERVICES);
var creds = env['mysql-5.1'][0]['credentials'];
console.log(creds)
var client = mysql.createConnection({
host: creds.host || "localhost",
user: creds.user,
password: creds.password,
port: creds.port,
database: "savelinks"
});
The code in app.js
var express = require("express");
var path = require("path");
var port = 9000;
var request = require('request');
var cheerio = require('cheerio');
var app = module.exports = express();
console.log(process.env.VCAP_SERVICES)
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
var server = require("http").createServer(app)
app.get("/", function(req,res){
res.render("index");
});
/*
* GET ALL LINKS ON LOAD PAGE
*/
app.get("/links", function(req, res){
links = db.client.query("SELECT * FROM links ORDER BY created DESC", function(err, result){
if(!err){
res.json(result)
}
});
});
// more routers
app.listen(process.env.VCAP_APP_PORT || port, function(){
console.log("server run in port " + port)
});
This is the log that app fog shows
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (/mnt/var/vcap.local/dea/apps/savelinks-0-ca19c96d36d4701debe7fe46752707c5/app/node_modules/mysql/lib/protocol/Protocol.js:73:13)
at Socket.onend (stream.js:66:10)
at Socket.EventEmitter.emit (events.js:126:20)
at TCP.onread (net.js:417:51)
Any idea for solve this problem?
I had the same kind of issue in production, but not on my personal development machine. My node server uses node-mysql with connect on an Ubuntu VM. My node server would crash and restart now and then throughout the day with the same kind of error you are seeing.
The following approach explained on the node-mysql GitHub page worked to solve the problem for me:
https://github.com/felixge/node-mysql#server-disconnects