I want to use my original html in node.js
This is simple hsh.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> How to Say Hello </title>
<link type="text/css" href="./sys/lib/css/uniform.default.css" rel="stylesheet" media="screen" />
<link type="text/css" href="./sys/lib/css/jquery-ui.1.10.3.smoothness.css" rel="stylesheet" media="screen" />
<script type="text/javascript" src="./sys/lib/scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="./sys/lib/scripts/jquery-ui.1.10.3.min.js"></script>
<script type="text/javascript" src="./sys/lib/scripts/myhello.js"></script>
<script>
$(function(){
$( "#sayDate" ).datepicker();
});
function resetHello()
{
document.getElementById("hello").value = "";
document.getElementById("sayDate").value = "";
}
</script>
</head>
<body>
<form name="syaHello">
How to say hello in your contry?<br>
<input type="text" id="hello" value="">
<INPUT id=sayDate style="WIDTH: 100px" name=sayTime>
</form>
<div class="docBtn_list">
<input type="button" value="View Hello" onclick="javascript:howHello();" />
<input type="button" value="Reset" onclick="resetHello();" />
</div>
</body>
</html>
myhello.js
function howHello()
{
alert(document.getElementById("hello").value + " " +
document.getElementById("sayDate").value);
}
and nodeSev.js
var http = require('http'),
fs = require('fs');
fs.readFile('./hsh.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(3000);
});
But this is not working about jquery and howHello java script.
I don't want change html and js too much and don't use express package.
Before answering your question...
Your question aims at serving static web content.
You should install 'express' (a node module based on famous 'connect', which can be used for this as well but lacks other features) and configure it to serve your file from a static directory:
var express = require('express');
var app = express.createServer();
/* configure your static directory */
app.configure(function(){
app.use(express.static(__dirname + '/static'));
});
/* on request, send index.html */
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
app.listen(3000);
Now that you have express installed, take a look at Jade.
You can then process received requests and dynamically serve content. That's state of the art - serving pre-coded html is 90's-style.
Related
I am building a real-time chat application using Node.js and socket.io.
I have built two js files - index.js for handling socket connection server requests and client.js for the client-side code. When I include console.log, I cannot get the output in the command line.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--connects server and client-->
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script src="./js/client.js"></script>
<link rel="stylesheet" href="./css/style.css">
<title>NiChat App</title>
</head>
<body>
<!--Navbar-->
<nav>
<img class="logo" src="logo.png" alt="Log">
</nav>
<!--Container for the chat app-->
<div class="container">
<div class="message" id="m-left">Palpatine: Did you ever hear the tragedy of Darth Plagueis the wise?</div>
<div class="message" id="m-right">Anakin: No.</div>
</div>
<!--Send box-->
<div class="send">
<form id="send-container" action="#">
<input type="text" name="msgInp" id="msgInp">
<button class="btn" type="submit">Send</button>
</form>
</div>
</body>
</html>
index.js
//file which will host the socket io
const io = require("socket.io")(8000)
const users = {};
io.on('connection', (socket) => { //io.on listens to several socket connections
console.log('a user connected');
socket.on('new-user-joined', Name => { //accepts an event 'new-user-joined'
console.log('New user', Name)
users[socket.id] = Name;
socket.broadcast.emit('user-joined', Name)
});
socket.on('send', message => {
socket.broadcast.emit('receive', { message: message, name: users[socket.id] })
});
})
client.js
const socket = io('http://localhost:8000');
const form = document.getElementById('send-container');const msgInp = document.getElementById('msgInp');const msgContainer = document.querySelector(".container")const Name = prompt("Enter your name to join");socket.emit('new-user-joined', Name)
The client.js file is within the js folder.
The index.js is within the node_modules folder.
Please help me out.
I tried putting console.log at different places of both the js files but am unable to produce an output.
This answer provided the solution to my question.
Here is the link
Adding this { transports: ['websocket'] } inside the io makes the problem go away.
This question already has an answer here:
Link index.html client.js and server.js
(1 answer)
Closed 1 year ago.
OVERVIEW
I am trying to create a Dapp with Ethereum and the course I am following (Udacity Blockchain Nanodegree Program) is asking us to create a HTML page from where a User using the page's buttons can interact with the Smart Contract. I am a beginner with HTML and anything related to hosting servers and routing, etc. So, I created two really basic functions in the Javascript file to practice how to call them and later on replace it with the correct web3 functions.
PROBLEM
The thing is that I've used a separated Javascript file for my functions and when I try to call those functions from the HTML file it doesn't work.
I've read that the main reason is that the functionFile.js is not in the server.js and it should have a route.
QUESTIONS
Why my code doesn't work? Could you explain it so that a beginner like me can understand it?
What is the code that I need to implement in server.js that will solve these errors and make the page work as intended?
PROJECT DIRECTORY STRUCTURE
SERVER.JS CODE
const http = require('http');
const fs = require('fs');
const PORT = 8080;
fs.readFile('./index.html', function (err, html) {
if (err) throw err;
http.createServer(function (request, response) {
response.writeHeader(200, { "Content-Type": "text/html" });
response.write(html);
response.end();
}).listen(PORT);
});
TEST.JS CODE
function letMeCallYou() {
alert("Bazinga!!! you called letMeCallYou");
}
function myfunction() {
document.write("welcome to Javatpoint");
}
INDEX.HTML CODE
<!DOCTYPE html>
<html lang="en">
<head>
<title>StarNotary DAPP Front End</title>
<meta name="viewport" content="width=device-width, initial-scale=1"
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
</head>
<style>
input {
display: block;
margin-bottom: 12px;
}
</style>
<body>
<h1>StarNotary DAPP</h1>
<h3 id='name'>Star Name: </h3>
<hr>
<h3 id='owner'>Star Owner: </h3>
<hr>
<h3>Claim Star</h3>
<hr>
<h3>TEST</h3>
<button id="test" onclick="letMeCallYou()">Testing External Javascript library</button>
<script src="scripts/test.js"></script>
<script>letMeCallYou();</script>
</body>
</html>
ERROR SCREENSHOT
So I managed to solve my problem after modifying the server.js file folder. Here is my updated project file architecture with the updated server.js code.
PROJECT ARCHITECTURE
SERVER.JS CODE
const express = require('express');
const app = express();
// THIS LINE WAS THE SOLUTION TO THE PROBLEM
app.use(express.static('./public'));
app.get('/', (req, res) =>{
res.setHeader('Content-type', 'text/html');
res.sendFile('./public/index.html');
});
app.listen(8080, () =>{
console.log('APPLICATION INITIALIZED....');
});
INDEX.HTML CODE
<!DOCTYPE html>
<html lang="en">
<head>
<title>StarNotary DAPP Front End</title>
<meta name="viewport" content="width=device-width, initial-scale=1"
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
</head>
<style>
input {
display: block;
margin-bottom: 12px;
}
</style>
<body>
<h1>StarNotary DAPP</h1>
<h3 id='name'>Star Name: </h3>
<hr>
<h3 id='owner'>Star Owner: </h3>
<hr>
<h3>Claim Star</h3>
<hr>
<h3>TEST</h3>
<button id="test" onclick="letMeCallYou()">Testing External Javascript library</button>
<script src='./scripts/app.js'></script>
</body>
</html>
EXECUTION SCREENSHOT
I'm trying to highlight every word on mouseover. I'm using node.js and express js.
Here is a fiddle as example : https://jsfiddle.net/gsrgfd8e/
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
//home
app.get('/', function(req, res) {
res.render('home');
});
// not found
app.get('*', function(req, res){
res.send('page not found');
});
app.listen(3000);
home.ejs
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://sites.google.com/site/aryandhaniblogv2/jquery-lettering-0-6-1-min/jQuery.lettering-0.6.1.min.js"></script>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
$(".word_split").lettering('words');
}//]]>
</script>
<style type="text/css">
#text{
width:60%;
margin: auto;
text-align:justify;
font-size:18pt;
}
.word_split span:hover {
background-color: #20B2AA;
color:white;
}
</style>
<title></title>
</head>
<body>
<div id="text">
<p class="word_split">Peki nedir bu Bulletproof Coffee? Efendim adından da anlayabileceğimiz gibi cumhurbaşkanının bilmemkaçyüzbindolar değerindeki aracı gibi kurşungeçirmez özelliği olduğuna inanılan, Batman’ e, Hulk’ a, Flash’ e, Black Widow’ a, Jon Snow’a, Kenan Komutan’a, Şebnem Ferah’a ve hatta ne istiyorsanız ona dönüşebileceğinizi vaat ettiği rivayet edilen bir kahve çeşidi. Bugüne dek birçok farklı kahve denemiş, hepsinden ağzınıza size düşen payı almış olmanız muhtemel fakat bu tarife kulak verseniz pek de kötü etmiş olmazsınız gibi geliyor.</p>
<p class="word_split">Size ölümsüzlük iksirinin bulunduğu müjdesini vermek isterdik lakin ne böyle bir iksir bulundu ne de buna gerek var. Size verdiği tek şey bünyeden bünyeye farklılık gösteren enerji etkisidir. Enerji dediysek öyle hemen içer içmez Galya’lı Asterix gibi Romalılara saldırmaya kalkmayın. Çünkü etkisi uzun zamanlı kullanımda kendini gösterecek bir kahve çeşididir. Tabi Obelix gibi kazana düşmediyseniz.</p>
<p class="word_split">Vakit kaybetmeden Bulletproof Coffee tarifimize geçerek kendimizi kurşungeçirmez yapalım.</p>
</div>
</body>
</html>
The page I get from localhost doesn't highlight the words like in the example. Javascript seems to work fine, after some testing. Maybe it's Jquery?
The headers for content type set by script you included :
<script type="text/javascript" src="https://sites.google.com/site/aryandhaniblogv2/jquery-lettering-0-6-1-min/jQuery.lettering-0.6.1.min.js"></script>
were having issue which you will find in console :
MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Solution :
Use express static content serving and add following in index.js
app.use(express.static(path.join(__dirname, 'public')));
now create a folder public/css inside your node server root and copy content of file https://sites.google.com/site/aryandhaniblogv2/jquery-lettering-0-6-1-min/jQuery.lettering-0.6.1.min.js into a new file lettering.js
And then finaly replace script tag with this :
<script type="text/javascript" src="css/lettering.js"></script>
I'm trying to build an app that lets me enter in information about an event and then have that pinned on a map. I'm stuck at the beginning though on actually saving the information. When I use Inspect in Chrome, it tells me it posted, but the data is blank. I'm pretty new to this kind of stuff and not sure where I'm going wrong.
The first file is the app.js where I set up the database, a simple partial schema, etc.
The second file is my dashboard.html that displays the map and the form. I was trying the onsubmit/javascript stuff which displays the data without refreshing the page, but ideally I want to be able to refresh the page and have the data still be posted somewhere.
Any help would be greatly appreciated! Thanks! :)
require('dotenv').config({ silent: false }); // Retrieve .env contents
var http = require('http'); // Basic HTTP functionality
var path = require('path'); // Parse directory paths
var express = require('express'); // Provide static routing to pages
var app = express();
var Router = require('router')
var router = Router()
var server = http.Server(app);
var port = 8080;
var app = setupExpress();
// Import mongoose module and connect the database
var mongoose = require('mongoose');
var mongoDB = 'mongodb://Username:Password#ds159180.mlab.com:59180/app-database';
mongoose.connect(mongoDB);
//Get the default connection
var db = mongoose.connection;
// Start server on port 8080
// localhost:8080
server.listen(port);
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//Define a schema
var Schema = mongoose.Schema;
var EventSchema = new Schema({
eventName : String,
eventType : String
});
var Event = mongoose.model('Event', EventSchema);
app.post('/dashboard', function(req, res) {
res.json(req.body); // req.body is your form data
});
app.post('/dashboard', function(req,res){
var content = new Event({
eventName : req.body.eventName,
eventType : req.body.eventType
}).save(function(err,doc){
if(err){
return handleError(err);
} else {
console.log('your form has been saved');
}
})
});
function setupExpress()
{
// Set default path for views and public
var viewsDir = path.join(__dirname, 'views');
var publicDir = path.join(__dirname, 'public');
app.use(express.static(publicDir));
// Root page is login form
app.get('/', function(req, res)
{
res.sendFile('views/index.html', { root: '.' });
});
// Once logged in, home page is dashboard
app.get('/dashboard', function(req, res)
{
res.sendFile('views/dashboard.html', { root: '.' });
});
// Redirect to error page if there's an issue
app.use(function(err, req, res, next)
{
console.log(err.stack);
res.status(err.status || 500);
res.sendFile('/views/error.html', { root: '.' });
});
return app;
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Web browser tab title -->
<title>App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../css/sb-admin-2.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="../vendor/morrisjs/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript"
src="http://www.your-domain.com/easy-comment/jquery.easy-comment.min.js"></script>
<title>App Tester</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-8" style="margin-top: 30px">
<div class="panel panel-default">
<div class="panel-heading text-center">
<i class="fa fa-map-marker fa-3x"> Add Event</i>
</div>
<div class="panel-body">
<div class="col-lg-6">
<form id="eventForm" method="post" onsubmit="return false">
<div class="form-group">
<label for="eventName">Event Name</label>
<input type="text" class="form-control" id="eventName" placeholder="Event name">
</div>
<div class="form-group">
<label for="eventType">Type</label>
<select class="form-control" id="eventType">
<option>Study Group</option>
<option>Food</option>
<option>Meeting</option>
<option>Danger</option>
</select>
</div>
<div class="form-group">
<label for="eventLocation">Location</label>
<select class="form-control" id="eventLocation">
<option>Location 1</option>
<option>Location 2</option>
<option>Location 3</option>
</select>
</div>
<div class="form-group">
<label for="eventNotes">Event Notes</label>
<textarea class="form-control" id="eventNotes" rows="2" placeholder="Add details about your event"></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<div id="confirm"><div>
<script type="text/javascript">
var txt = document.getElementById("eventName");
document.getElementById("eventForm").addEventListener("submit", confirmdata);
function confirmdata(event) {
event.preventDefault();
var eventName = txt.value;
document.getElementById("confirm").innerHTML += '<p>Name: ' + eventName + '</p>';
}
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
You should use body-parser to change your data post from client to json
var bodyParser = require('body-parser')
app.use(bodyParser.json())
You can get json data via req.body
her is my app.js which is confugaration file of express.js
<
var express = require('express')
, argv = require("optimist").argv
, fs = require("fs")
, hbs = require("hbs")
, WatsonClient = require("watson-js");
var clientId = argv.key || '5b1cb9a9c097e1100eeeebaf66117265'
, clientSecret = argv.secret || '01b8417ac6872450'
, appPort = argv.port || '3000';
function cp(source, destination, callback) {
// Read a buffer from `source`
fs.readFile(source, function(err, buf) {
if (err) { return callback(err); }
// Write that buffer to the new file `destination`
fs.writeFile(destination, buf, callback);
})
}
var Watson = new WatsonClient.Watson({ client_id: clientId, client_secret: clientSecret });
var app = express();
app.configure(function() {
console.log('inside function');
// Set the location of views and type of view engine
app.set('views',__dirname + '/app/views');
console.log(__dirname + '/app/views');
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
console.log('after view');
// Set up a standard Express configuration
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({
secret: "This is an example."
}));
app.use(app.router);
console.log('before public');
// Set the location of static assets
app.use(express.static(__dirname+'/public'));
console.log(__dirname+'/public');
console.log('after public');
});
app.get('/', function(req, res) {
res.render('layout');
});
app.post('/upload', function(req, res) {
cp(req.files.upload_file.filename.path, __dirname + req.files.upload_file.filename.name, function() {
res.send({ saved: 'saved' });
});
});
app.post('/speechToText', function(req, res) {
// Traditionally, you would store this access token somewhere safe like a database. For the purposes of this example, we're going to generate a new one on the first request and store it in the session so we don't have to deal with a database or tracking expiry and refreshing access tokens.
if(!req.session.accessToken) {
// !AT&T API: Get Access Token
Watson.getAccessToken(function(err, accessToken) {
if(err) {
// Handle an error getting an access token
res.send(err);
return;
} else {
req.session.accessToken = accessToken;
token.
Watson.speechToText(__dirname + '/public/audio/audio.wav', req.session.accessToken, function(err, reply) {
if(err) {
res.send(err);
return;
}
res.send(reply);
return;
});
}
});
} else {
Watson.speechToText(__dirname + '/public/audio/audio.wav', req.session.accessToken, function(err, reply) {
if(err) {
res.send(err);
return;
}
return;
});
}
});
app.listen(appPort);
console.log('AT&T Speech API Basic Walkthrough App started on Port ' + appPort + '.');
// !USAGE: node app.js --key= --secret= --port=
// !SETUP: Dependencies
/*
* Express: Minimal web application framework
* FS: Node.js File System module
* Optimist: Lightweight option parsing
* HBS: Express View Engine wrapper for Handlebars
* Watson.js: Simple API Wrapper for the AT&T Speech API
*/
and my layout.html is
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>AT&T Speech API Example: Basic Walkthrough</title>
<meta name="description" content="Application for the AT&T Speech API Deep Dive Presentation at DevLab 2012">
<meta name="author" content="Michael Owens">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="public/styles/bootstrap.css">
<link rel="stylesheet" href="public/styles/example-basic.css">
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js'></script>
</head>
<body>
<a onclick="Recorder.playBack('audio');" href="javascript:void(0);" title="Play">
Play
</a>
<div class="container">
<div class="row">
<div class="span12">
</div>
</div>
<div class="row">
<div class="span4">
<h2 id="progress-title">Progress (Step <span id="progress-step">1</span> of 5)</h2>
<div id="progress-indicator" class="progress progress-striped">
<div class="bar" style="width: 20%;"></div>
</div>
<ol class="progress-list">
<li id="progress-01" class="active">Access User's Microphone</li>
<li id="progress-02">Record Audio from Mic</li>
<li id="progress-03">Save Audio to File</li>
<li id="progress-04">POST File to AT&T Speech API</li>
<li id="progress-05">Receive Results from AT&T Speech API</li>
</ol>
<div>
<i class="icon-refresh"></i> Start Over
</div>
</div>
<div class="span8">
<h2>Current Status</h2>
<div id="status-mic" class="alert alert-info">
Audio Status: <strong>waiting</strong>
</div>
<div id="status-upload" class="alert alert-info">
File Status: <strong>waiting</strong>
</div>
<div id="control_panel">
<div class="btn-group">
<button id="button-connect" class="btn btn-large btn-success"><i class="icon-off icon-white"></i> <span class="action">Connect</span></button>
<button id="button-recorder" class="btn btn-large" disabled="disabled"><i class="icon-music"></i> <span class="action">Record</span></button>
<span id="button-save" class="btn">
<button disabled="disabled" class="btn btn-large"><i class="icon-download-alt"></i> <span class="action">Save</span></button>
<span id="save_button"><span id="flashcontent"></span></span>
</span>
<button id="button-transcribe" class="btn btn-large" disabled="disabled"><i class="icon-share-alt"></i> <span class="action">Transcribe</span></button>
</div>
</div>
<div id="transcribe-container">
<h2>Speech API Response</h2>
<div id="transcribe-response"></div>
</div>
</div>
</div>
<form id="uploadForm" name="uploadForm" action="/upload" >
<input name="authenticity_token" value="xxxxx" type="hidden">
<input name="upload_file[parent_id]" value="1" type="hidden">
<input name="format" value="json" type="hidden">
</form>
<script type="text/javascript" src="public/scripts/swfobject.js"></script>
<script type="text/javascript" src="public/scripts/example-basic.js"></script>
</div>
</body>
</html>
When i run app.js on node in cmd, it gives me error of not able to load static files i.e js and css files but it load view part i.e layout.html
exact errors is
<
GET h://ip:3000/public/scripts/swfobject.js 404 (Not Found)
GET h://ip:3000/public/scripts/example-basic.js 404 (Not Found)
GET h://ip:3000/public/styles/bootstrap.css 404 (Not Found)
GET h://ip:3000/public/styles/example-basic.css 404 (Not Found)
>
ip -localhost
h -https
my foldr structute is
example(parent folder)
subfolders
app/views/layout.html(code is given above)
public/scripts/js files
public/styles/css files
app.js(code is given above)
all the above subfolder(app,public,app.js) at the same level
so please suggest me some thing
It should work if you remove the 'public' from your URLs, like:
<link rel="stylesheet" href="/styles/bootstrap.css">
<link rel="stylesheet" href="/styles/example-basic.css">
You setup the static directory to be /public so its going to look in there for static resources. You did that here:
app.use(express.static(__dirname+'/public'));
When you add public to those URLs, it will be looking in /public for a folder called public, which it won't find. It will however find a folder called styles.