Serving HTML, CSS and JS using Node.js and Express.js - html

const express = require('express');
const path = require('path');
const app = express ();
app.use(express.json('public'))
app.get('/PKorn/zealtech', function(req, res) {
res.sendFile(path.join(__dirname, '/public/Ko.html'));
});
app.listen(4402);
when i using /PKorn is work with css but when i use /PKorn/zealtech work page but css is missing

Try to change app.use(express.json('public')) to app.use(express.static('public')).

Related

.JS Not running on VS Code

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 ?

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.

nodeJs display on web browser

Just want to display my node.js result on web browser..
is it possible?...
here's my code:
const testFolder = 'texts/';
const fs = require('fs');
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
})
when I try to run that code on cmd it works. The code gets all the .txt file on a specific directory.
here's the result:
then when i tried to load it on my browser the result goes like this
Im also planing to add all the result filename to database mysql once the node.js code fixed.. is that also possible?..
thank you.. this is my first time to create a node.js
Use the express router to accept GET request from your browser :
const express = require('express');
const fs = require('fs');
const app = express();
const testFolder = 'texts/';
// To set your public directory and use relative url
app.use(express.static(__dirname + 'your_public_dir'));
// When you access to localhost:8080, it will send GET '/' request
app.get('/', function(req,res) {
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});
});
Nicolas is right, express can achieve this. Just remember to install it using NPM, this can be done by executing following command under the directory where package.json is:
npm install --save express
however, you would also need to write into response of the server so it shows on website. So for example, using Express:
app.get('/', function(req,res) {
res.write("whatever you want to display");
res.end()
});

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

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?

ExpressJS POST cannot log body

After a lot of fiddling with upgrading versions and the different middleware/ways of using a body parser, I am still stuck.
I have an Iphone app which POSTs 2 things (2 separate things). First is an image, which works.
Second is a json object which i try to put into mongodb.
No matter what i do, i can't seem to log the contents of the request.
var express = require('express');
var logger = require('morgan');
var fs = require('fs');
var json = require('express-json');
var path = require('path');
var errorHandler = require('errorhandler');
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
FileDriver = require('./fileDriver').FileDriver;
...
app.use(json());
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
...
app.post('/:collection', function(req, res) {
console.warn(req.body.poi.toString());
var object = req.body;
var collection = req.params.collection;
console.warn("Post: " + req.toString());
collectionDriver.save(collection, object, function(err,docs) {
if (err) { res.send(400, err); }
else { res.send(201, docs); }
});
});
I've tried logging (log, warn) req.body, req, etc. to no avail.
i'm using express-json and NOT url encoding, don't think need it.
morgan ouputs the following when i post
POST /pois 200 15.983 ms - 63
and nothing else!
It apparently cannot do it, as stated in this closed issue https://github.com/expressjs/morgan/issues/16
morgan is not intended for this kind of work. Try and use Winston instead, or simply console.log
This does it for me:
const express = require('express')
const app = express()
app.use(express.json())
var morgan = require('morgan')
morgan.token('response-body', (req, res) => {return JSON.stringify(req.body)}); // define 'response-body' token using JSON.stringify
app.use(morgan(':method :url :response-time :response-body')) //include newly defined ':response-body' token
app.post(/....)