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

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

Related

trouble in sending data through ajax to express server

I'm new to backend and I was having some trouble in sending data through vanilla ajax to my express server.
please tell me where am I going wrong
my ajax request:
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.withCredentials = true;
xhttp.send("name=abhishek");
my express server:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors({
credentials:true,
origin:'http://127.0.0.1:5500'
}));
var PORT = process.env.PORT || 8080;
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/', function(req, res){
console.log(req.query);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
I'm receiving an empty object as the output in my console
There are few things to change.
The client is a POST request but in server side, it is a GET app.get(). Therefore, nothing displayed after request.
Also, Content-type needs to be set to inform server how it is going to parse the message. e.g. JSON/form-data
I assume you want to use POST, below is the change:
Backend:
Change method from app.get to app.post
Get the data from body instead of query
...
app.post("/", function (req, res) {
console.log(req.body); // data is in body instead of query
res.send("hi"); // send back response to frontend
});
...
Frontend:
Set content-type
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(xhttp.responseText); // should receive hi
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.withCredentials = true;
xhttp.send("name=abhishek");

NodeJS reload page but don't send user data again [duplicate]

This question already has answers here:
How to prevent form resubmission when page is refreshed (F5 / CTRL+R)
(21 answers)
Closed 4 years ago.
I have a Node Js local server and several identical html pages. On every page I save some user data input fields saved simply on a text file. My problem is that if the users refresh the page the data from the previous html page is send again and again saved on the text file. Is there a way to prevent this?
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8000;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + "/public"));
app.use('/images', express.static(__dirname +'/images'));
app.listen(port, function(){
console.log('server is running on ' + port);
});
app.get('/', function(req, res){
res.sendfile('intro.html');
});
app.post('/userID', function(req, res){
//save the userID on a text file
var userID= req.body.userID + ';';
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
return res.sendfile('main.html');
});
app.post('/submit', function(req, res){
res.sendfile('main2.html');
});
Furthermore, I have also a refresh button that does the same as the browser refresh button. I s there a way to avoid the same problem?
<button>Reset</button>
and its JavaScript:
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', clickHandler);
});
function clickHandler(element) {
location.reload();
}
Thank you in advance!
You can use fs.readFile and check if that file contain that userId
If that is not present then append or else dont append
fs.readFile('temporary/userID.txt', function (err, fileData) {
if (err) throw err;
if(fileData.indexOf(userID) == -1){
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
}
});
So, the code will be:
app.post('/userID', function(req, res){
//save the userID on a text file
var userID= req.body.userID + ';';
fs.readFile('temporary/userID.txt', function (err, fileData) {
if (err) throw err;
if(fileData.indexOf(userID) == -1){
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
}
});
return res.sendfile('main.html');
});

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?

sending json data response

I am trying to send a JSON response via HTTP but unfortunately, I don't see any response, I cant understand why really.
It looks like the response variable is not being sent.I am not sure the problem is that it is a JSON object or the way I am sending it.I am new to web development.
The requirement is to help user see the time and the name of the file which was usccessfully sent through.
var express = require('express');
var fs = require('fs');
var cors = require('cors');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = express();
var upload = multer({ dest: 'uploads/' });
var Client = require('ssh2').Client;
const request = require('request');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.get('/', function(req, res){
console.log('GET /');
//var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
var html = fs.readFileSync('index.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
app.post('/', upload.single('file'), function(req, res){
var response;
var time;
console.log('POST /');
console.dir(req.body);
// console.log(req.body.filename);
fs.writeFile('./uploads/' + req.body.filename, req.body.file,
function(err) { console.log(err)});
var conn = new Client();
conn.on('ready', function() {
console.log('Client :: ready');
conn.sftp(function(err, sftp) {
if (err) throw err;
// sftp.fastPut('./uploads/' + req.body.filename, '/data/' +
req.body.filename, function (err) {
// if (err) {
// console.log(err);
// throw err;
// }
// });
sftp.readdir('data', function(err, name) {
if (err) throw err;
console.dir(name);
var infoList = JSON.parse(JSON.stringify(name));
for(var index in infoList) {
var value = infoList[index];
time = value.attrs.mtime;
console.log(value.filename);
console.log(time);
response = JSON.stringify(value.filename);
}
conn.end();
});
});
}).connect({
host: 'ftp.amadeus.net',
port: 15022,
username: 'wtl001',
password: 'Wyamp309$'
});
res.writeHead(200, {'Content-Type': 'application/json', "Access-Control-
Allow-Origin": "*"});
res.json(response);
res.end("EOF");
});
port = 12811;
app.listen(port);
console.log('Listening at http://localhost:' + port);

Return undefined answer from multer

I am using multer in my nodejs application for uploading files. And angularjs for the front end part. Once I click upload image, on the console I am getting undefined answer. Can any one help me to solve the problem.
Here I am pasting the code.
server.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;
var multer = require('multer');
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'public/upload/');
},
filename:function(req,file,cb){
cb(null,file.originalname);
}
});
var upload = multer({storage: storage});
app.set('views', __dirname + '/views');
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use(express.static('public'));
app.get('/',function(req,res){
res.render('index',{ title: 'Upload image' });
});
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
http.listen(8080,'0.0.0.0',function(){
console.log('listening on 8080');
})
And here is my app.js angularjs code
var app = angular.module('app',['ui.router','ui.bootstrap','ngAnimate']);
$scope.img={};
app.controller('Ctrl',function ($scope,$http){
$scope.loadImage = function(){
$http.post('/loadImage',$scope.img).success(function(data){
console.log('Posted successfully');
}).error(function(data){
console.error('error');
})
};
And my HTML code:
<form ng-submit="loadImage()" enctype="multipart/form-data">
<input type="file" name="file" multiple />
<input type="submit" value="Upload Image" name="submit" />
</form>
On the console I am getting Undefined and Inside post. And on the browser console I am getting posted successfully Can any one please help me to solve this. Instead of undefined I should get loaded file information.
This how i used Multer to upload an image
var multer = require('multer');
exports.loadImage = function (req, res) {
var upload = multer({
inMemory: true,
limits: {fileSize: 1024 * 1024 }
}).single('newPicture');
upload(req, res, function (uploadError) {
if (uploadError) {
return res.status(400).send({ message: 'errorUploadingPicture' });
}
else {
var profileImage = 'No data uploaded';
// this is where the photo data is
if (req.file && req.file.buffer) {
profileImage = req.file.buffer;
}
return res.json(profileImage );
}
});
};
This is all assuming you are sending your file correct
try
var uploadType = upload.any()
and change
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
to
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});
if you are attempting to only get one file at a time then instead,
var uploadType = upload.single('file')
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});