So I just made a HTML page added a script tag with src to a js file and sent the HTML file as response with node js using HTTP module.
But the js file is not working and when I checked the network tab I saw js file is received as text/html file.
Following are the js and html codes.
Server code with node js
const http = require('http') ;
const file = require('fs') ;
const server = http.createServer((req, res) => {
file.readFile('public/login.html', (err, data) => {
if (err) throw err ;
res.writeHead(200, {'Content-Type': 'text/html'}) ;
res.write(data) ;
res.end() ;
})
}) ;
server.listen(5000) ;
front end code : login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<script defer src="js/index.js"></script>
</head>
<body>
<h1>Login</h1>
<form action="" method="post">
<input type="email" name="user" id="user">
<input type="password" name="pass" id="pass">
<button type="submit" name="button" value="login">Login</button>
</form>
</body>
</html>
now when I load the page at localhost:5000, js does not execute and it's received as text/html.
The browser will receive the HTML, see the script tag, and request js/index.js from your server. But your server only sends your HTML file. It doesn't pay any attention to what the browser requested, it just always sends back the HTML. So the script is never sent to the browser, so the browser can't execute it.
Your server code needs to look at req to determine what was requested (looking at url, etc.), and send an appropriate response, rather than always sending back the same content.
Here's a fairly simple example that handles /, /login.html, and /js/index.js paths (making the first two synonyms):
const http = require('http');
const file = require('fs');
const FILENAME_404 = "public/404.html";
const server = http.createServer((req, res) => {
let filename = null;
let contentType = "text/html";
let status = 200;
// What did the browser ask for?
switch (req.url.toLowerCase()) {
case "/":
case "/login.html":
// The login page
filename = "public/login.html";
break;
case "/js/index.js":
// The JavaScript file
filename = "public/js/index.js";
contentType = "text/javascript";
break;
default:
// Something we don't support -- send a 404
filename = FILENAME_404;
status = 404;
break;
}
sendFile(res, filename, contentType, status);
});
function sendFile(res, filename, contentType, status, callback) {
file.readFile(filename, (err, data) => {
if (err) {
// Couldn't read the file, send a 404
if (filename !== FILENAME_404) {
sendFile(res, FILENAME_404, "text/html", 404);
} else {
// Couldn't even find the 404 file, send a minimal plaintext 404
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("The requested resource does not exist on this server.");
res.end();
}
} else {
res.writeHead(status, {"Content-Type": contentType});
res.write(data);
res.end();
}
});
}
server.listen(5000);
Note: This is just an example. If you're going to build anything of any size, you'll want more structure than this. You might look at Express or Koa or others that handle more of the HTTP plumbing, URL routing, etc. for you and have modules available for other things as well.
Related
(Please correct my terminology if it's not correct.)
My files server.js, run.js and index.html, are in the same directory.
server.js
Sets up the server.
const express = require('express');
const path = require('path');
const run = require('./run.js');
var app = express();
app.get('/index.html', function(req, res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/', function(req, res){
res.redirect('index.html');
});
app.post('/run', async function(req, res){
var data = await run.run();
res.json(data);
});
app.listen(5000, function () {
console.log('Dev app listening on port 5000');
});
run.js
Will contain functions that consumes time. Here just one function as example:
async function run(){
//do time consuming stuff
var data = {
"status" : "ok",
"a1" : 1,
"a2" : 2
};
return data;
}
module.exports = {
run:run
}
index.html
Simple form.
<!DOCTYPE html>
<html>
<body>
<form id="search-form" action="/run" method="post">
Input:<br>
<input type="text" name="input1" id="input1" value = ""> <br>
<input type="submit" value = "Run">
</form>
<script></script>
<div id="data"></div>
</body>
</html>
When I run the server, go to localhost:5000 in the browser, and click the run button, I get redirected to a page just showing the content of data.
What I would like to happen when I click the the run button is;
The server process /run post request
A response is sent with res.json or res.send to the client
A javascript script on the client side should catch the response, process it, and make some change to the html code (in my case, create some table).
How can I achieve this?
So your problem is that you're using a form. Forms will redirect you to the specified web page with all of the form's data.
You need an XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.open("POST", "/run", true);
xhr.send();
If you ever need the data of your form to be submitted as well, I have some documentation on how to do that.
Hope this helps!
so I've created this application that allows me to call a phone number from my Twilio account through localhost. I just have to put a / after the port # and the phone number I want to call(localhost:2222/7786453738) and it will send out a call. but I want the user to be able to make that call by inputting a phone number on to the webpage then clicking a button. is that possible? here's my code so far in the index.js file. I run it by going node index.js in the command terminal.
const express = require("express");
const app = express();
const port = 2222;
app.get("/", function(req, resp){
resp.end("welcome to my app");
});
app.get("/:data", function(req, resp){
var accountSid = 'accountSid'
var authToken = 'authtoken'
var client = require('twilio')(accountSid, authToken);
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: req.params.data,
from: '6043302056',
}, function(err, call) {
if(err) {
console.log(err);
} else {
console.log(call.sid);
}
})
console.log(req.params.data);
if(req.params.data == "me"){
resp.end("hi raj");
//resp.sendFile(__dirname+"/public/index.html)
} else {
resp.end("Now calling: "+req.params.data);
}
});
app.listen(port, function(err){
if(err){
console.log("error starting "+err);
return false;
}
console.log("port is running. "+port);
})
Twilio developer evangelist here.
You're most of the way there with what you want to achieve. You can absolutely create a form that will take an input from a user and dial the number they enter.
First up, You will want to update your route as the number you send through a form won't be a part of the path, instead it will come as part of the body of the request. In order to read request bodies in express, you will want the body-parser module. So, install that in your project with:
npm install body-parser --save
Then include it in your file and use it with your app:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
Now, form's usually POST their data, rather than working over GET, so let's update your route to receive that POST request and extract the number from the request:
app.post("/calls", function(req, resp) {
const accountSid = 'accountSid'
const authToken = 'authtoken'
const client = require('twilio')(accountSid, authToken);
const number = req.body.number;
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: number,
from: '6043302056',
}, function(err, call) {
if(err) {
console.error(err);
} else {
console.log(call.sid);
}
})
console.log(number);
if(req.params.data == "me"){
resp.end("hi raj");
//resp.sendFile(__dirname+"/public/index.html)
} else {
resp.end("Now calling: " + number);
}
});
Now, you need an HTML file that will include a form to make the request to this endpoint. Create an HTML file called index.html and place it in a new folder in your application called public.
You can load static files from the public directory in express with this line, add it near the top, after you create the app:
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));
Finally we just need the HTML. This is the simplest HTML I could write that would do what you need:
<!DOCTYPE html>
<html>
<head>
<title>Make a call</title>
</head>
<body>
<form action="/" method="POST">
<label for="number">What number do you want to call?</label>
<input id="number" type="tel" />
<button type="submit">Make call</button>
</form>
</body>
</html>
As you can see it is just a form with a single input, the number, and a button to submit it.
Give this all a go and let me know how you get on.
Yes,
first: you can do that, but you need to write the code in HTML File or at least include this code in html file, and call the Twilo's function after you click on the respective button. For that first, render a HTML page, after user enters the address, on that HTML Page give input number and call now button feature. and after user clicks on the button, do:
function callNow() {
var num = document.getElementById('number').value;
client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: num,
from: '6043302056',
}, function(err, call) {
if(err) {
console.log(err);
} else {
console.log(call.sid);
}
{
Your HTML Code should be:
<input id="number">
<button onclick="callNow()">Call Now</button>
You can include twilio cdn and use this feature. I am just giving you the concept, I hope you will find this helpful.
I am trying to build a Node.js/AngularJS app with Openshift 2. The server is being run successfully and if I go to local adress I get index.html(but blank as it does not load the css), I cant get scripts and links on index.html, I get an error 404 but I dont know why.
Folder structure:
sw [sw master]
pages
index.html
inicio.html
css
inicio.css
js
angular.js
aplicacion.js
app.js
start.js
app.js
const http = require('http'),
fs = require('fs'),
path = require('path'),
contentTypes = require('./utils/content-types'),
sysInfo = require('./utils/sys-info'),
env = process.env;
let server = http.createServer(function (req, res) {
let url = req.url;
if (url == '/') {
url += '/index.html';
}
// IMPORTANT: Your application HAS to respond to GET /health with status 200
// for OpenShift health monitoring
if (url == '/health') {
res.writeHead(200);
res.end();
} else if (url == '/info/gen' || url == '/info/poll') {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache, no-store');
res.end(JSON.stringify(sysInfo[url.slice(6)]()));
} else {
fs.readFile('./pages' + url, function (err, data) {
if (err) {
res.writeHead(404);
res.end('Not found');
} else {
let ext = path.extname(url).slice(1);
if (contentTypes[ext]) {
res.setHeader('Content-Type', contentTypes[ext]);
}
if (ext === 'html') {
res.setHeader('Cache-Control', 'no-cache, no-store');
}
res.end(data);
}
});
}
});
server.listen(env.NODE_PORT || 3000, env.NODE_IP || 'localhost', function () {
console.log(`Application worker ${process.pid} started...`);
});
index.html
<!DOCTYPE html>
<html lang="es" data-ng-app="TFG">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Página principal</title>
<script src="../js/angular.js"></script>
<script src="../js/app.js"></script>
<link href="../css/inicio.css" rel="stylesheet" />
</head>
<body>
<!--CUERPO-->
<div data-ng-view></div>
</body>
</html>
your index file should be at root level as you are providing path in your nodejs file.
Right now your index.html is under "pages" folder.
pages
index.html
inicio.html
I think this will be your tree
sw [sw master]
pages
inicio.html
css
inicio.css
js
angular.js
aplicacion.js
emphasized textindex.html
app.js
start.js
The Node.js script running the server will render html from page folder. This index.html has the css and js linked by relative path from the folder structure but you need to expose that publicly too to get reached by the browser when it tries to get the resources. You will need some code to serve that static content.
In fact, is your own code returning that 404 as the URL that the browser is trying to get the resources (css and js) from your pages folder and they are not found.
fs.readFile('./pages' + url, function (err, data) {
if (err) {
res.writeHead(404);
res.end('Not found');
}
You should include some code that return the css and js files.
My code shows a simple upload form (node-formidable and node.js). I am using socket.io to update the client on it's current upload file progress. My problem is that I currently emit the progress update to every clients. As an example, if I start an upload with clientA, then connect to the website with clientB, clientB will see the exact same progress bar as clientA. Normally, clientA and clientB should be different, with their own respective progress bars, linked only with their respective uploads.
This is my app.js file
// Required modules
var formidable = require('formidable'),
http = require('http'),
util = require('util'),
fs = require('fs-extra');
// Path to save file, server side
var savePath = "./uploadedFiles/";
// Loading index.html
var server = http.createServer(function(req, res) {
// Form uploading Process code
//Upload route
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// creates a new incoming form.
var form = new formidable.IncomingForm();
// set the path to save the uploaded file on server
form.uploadDir = savePath;
// updating the progress of the upload
form.on('progress', function(bytesReceived, bytesExpected) {
io.sockets.in('sessionId').emit('uploadProgress', (bytesReceived * 100) / bytesExpected);
});
// parse a file upload
form.parse(req, function (err, fields, files) {
res.writeHead(200, { 'content-type': 'text/plain' });
res.write('Upload received :\n');
res.end(util.inspect({ fields: fields, files: files }));
});
form.on('end', function (fields, files) {
/* Temporary location of our uploaded file */
var temp_path = this.openedFiles[0].path;
/* The file name of the uploaded file */
var file_name = this.openedFiles[0].name;
/* Files are nammed correctly */
fs.rename(temp_path, savePath + file_name, function(err) {
if ( err ) console.log('ERROR: ' + err);
});
});
return;
}
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// socket.io
var io = require('socket.io').listen(server);
io.on('connection', function (socket) {
socket.join("sessionId");
});
server.listen(8080);
This is my index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Test d'upload</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('uploadProgress' , function (progress){
document.getElementById("currentProgress").value = progress;
});
</script>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
<p><progress id="currentProgress" value="0" max="100"></progress></p>
</body>
</html>
I do not have more code than this. I am new to node.js and socket.io, so I am not sure about the interactions between them and between the client and server.
How can I change my code to update only the right client?
Thank you anyway for your time.
a suggestion
there is a basic way
socketIO.sockets.socket(this.socketid).emit(<event>, dataObj);
if your function is inside your socket code...otherwise I will often do something like this
connection.query("select socketid from websocket_sessions where user_id=" + data.form.user_id, function(err, users) {
socketIO.sockets.socket(users[0].socketid).emit(<event>, dataObj);
});
where I am always updating or a
I'm trying to write my first Nodejs server for getting to know Angular/Node and eventually the whole MEAN stack.
My server is running but there's a problem in my code, for some reason when I enter a non existing file, it should redirect to 404, but it doesn't. For some reason the URL gets a double dash;
How would I go about making the redirect to 404 work?
check this image
Here is my code for the server so far.
var http = require('http'),
fs = require('fs'),
path = require('path'),
root = __dirname + '/public/', //magic var
mime = require('mime');
//Server
var server = http.createServer(function (req, res) {
// Check is root is queried
var fileName = '';
var url = req.url;
if (url === '/'){
url = 'index.html'; // redirect when no file specified
}
fileName = root + url;
// check if file exists
fs.exists(fileName, function(exists){
if (exists) {
serveFile(fileName); // yes
} else {
path = root + '404.html'; //no
serveFile(fileName);
}
})
//serve file
function serveFile(requestFile) {
// maak a stream based on events
var stream = fs.createReadStream(requestFile);
res.writeHead(200, {'Content-Type': mime.lookup(requestFile)});
stream.on('data', function (chunk){
res.write(chunk);
});
stream.on('end', function(){
res.end();
});
stream.on('error', function(err){
console.log('error: '+ err);
});
}
});
server.listen(3000); //server start
console.log('Server gestart op http://localhost:3000 ');
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>angular</title>
<link href="https://cdn.jsdelivr.net/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="styles/app.css" rel="stylesheet"/>
</head>
<body ng-app class="bg">
<h1>First name?</h1>
<input type="text" placeholder="Type your name" ng-model='firstName'
class="input-lg"/>
<p>
Hi, {{firstName}}
</p>
<img src="https://static.pexels.com/photos/7720/night-animal-dog-pet.jpg" height="100px" width="100px"/>
</body>
<script type="text/javascript" src="https://cdn.jsdelivr.net/angularjs/1.5.5/angular.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/angularjs/1.5.5/angular.min.js"></script>
</html>
Could anyone tell me what's going wrong here?
Thanks in advance!
get rid of the '/' after public:
root = __dirname + '/public'
It is the default behaviour of Node JS. ie. If you request for xxx.com/sample.txt, then the req.url will be "/sample.txt".
https://nodejs.org/api/http.html#http_message_url
So you have consider that in your code, as #Jordan mentioned, remove the "/".
Your redirect also should work fine.