how to set index.html to another page, not homepage - html

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?

Related

images not showing when using node js with handlebars(.hbs)

I have tried to search for an answer here but nothing so far worked, not many threads about handlebars.
I am struggling to get images to show up on my node app.
I have this on app.js and below that the code i am trying to get image to show up on the .hbs file:
const express = require("express");
const path = require("path");
const hbs = require("hbs");
const app = express();
const bodyParser = require("body-parser");
const port = process.env.PORT || 80;
require("./db/conn");
const SwimmingCollection = require("./models/schema");
const static_path = path.join(__dirname, "../public");
const template_path = path.join(__dirname, "../templates/views");
const partials_path = path.join(__dirname, "../templates/partials");
app.use(express.static(static_path));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "hbs");
app.set("views", template_path);
hbs.registerPartials(partials_path);
app.get("/", (req, res) => {
res.render("index");
});
app.listen(port, () => {
console.log(`Listening to the port at ${port}`);
});
How to fix this issue?
Try below line for Static Path.
app.use(express.static(path.join(__dirname, 'public')))
https://expressjs.com/en/starter/static-files.html

CSS Style issue using Express.js

const express = require("express");
const bodyParser = require("body-parser");
const request= require("request");
const app = express();
var path = require("path");
app.use("/fonts", express.static(path.join("fonts")));
app.use("/images" , express.static(path.join("images")));
app.use("/css", express.static(__dirname + '/css.main.css'));
app.get("/", function(req,res){
res.sendFile(path.join(__dirname, '../', 'index.html'));
});
app.listen(3000, function(){
console.log("server is up and running")
})
Here, I can't seem to find a solution to this problem. My CSS and fonts and images are not working.

Node js express can't parse body after routes moved into own folder

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
}));

Gets Error when adding MySQL information in server.js when creating RESTful API with Express

I was following instructions to build a RESTful API with Express and MySQL(*1)
But when I change
app.listen(port); //excutable, GET returns welcome message
into
orm.initialize(WConfig.config,function(err,models){
...
in the part 2 of(*1), which is adding MySQL information into server.js,
I gets the following on Node.JS command prompt:
TypeError: Cannot read property 'bear' of undefined
Because this is the first attempt in building RESTful API, I'm not sure what to do to fix it. Help please! Any idea is appreciated.
full code of server.js:
// server.js
var util = require('util');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Waterline = require('waterline');
var Bear = require('./app/models/bear');
var WConfig = require('./app/config/waterline');
var orm = new Waterline();
orm.loadCollection(Bear);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'hello! welcome to our api!' });
});
app.use('/api', router);
// express deprecated res.json(obj,status): use res.status(status).json(obj) instead
router.route('/bears')
.post(function(req,res) {
app.models.bear.create(req.body,function(err,model) {
if(err) return res.status(500).json({ err,err });
res.json(model); //res.json(model) , guess: res.status(200).json(model);
console.log(util.inspect(model));
});
});
//gets error if I change it to following
//
orm.initialize(WConfig.config,function(err,models){
if(err) throw err;
app.models = models.collections;
//app.set('models',models.collections);
app.connections = models.connections;
app.listen(port);
console.log('Magic happens on port ' + port);
});
reference:
1.Create Restful API with Express and waterline (in Chinese)
https://segmentfault.com/a/1190000004996659#articleHeader2
2.Build a RESTful API Using Node and Express 4
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

How to connect static HTML and CSS files to Node.js application?

I try to show a (static) HTML webpage via Heroku. I have followed this tutorial: https://www.youtube.com/watch?v=gAwH1kSODVQ but after many attempts it is still not working.
I'm rather new to coding, so if you can give concrete examples that would be great!
The following files have been pushed to heroku:
server.js
package.json
Procfile.js
(folder) public with index.html, main.css
//Server.js file:
var express = require('express'); //require express module in server.js file
var app = express();
var mongojs = require('mongojs');
var db = mongojs('birthdaylist', ['birthdaylist']);
var bodyParser = require('body-parser');
var http = require('http');
var port = Number(process.env.PORT || 3000);
app.use(express.static(__dirname + '/public')); //connect to html file
app.use(bodyParser.json());
app.get('/birthdaylist', function(req, res) {
console.log("The server has received a GET request.")
db.birthdaylist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/birthdaylist', function(req, res){
console.log(req.body);
db.birthdaylist.insert(req.body, function (err, doc){
res.json(doc);
});
});
app.delete('/birthdaylist/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.birthdaylist.remove({_id: mongojs.ObjectId(id)}, function(err, doc){
res.json(doc);
});
});
app.listen(port, function () {
});
you should use:
app.listen(%PORT_NUMBER%, function () {
// some code here
});
Instead of:
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end('<h6>Hello worldsfasfd!</h6>');
});