I'm using a Node.js server to show an HTML file. The HTML uses a Javascript file to get some info but I'm not being able to access that file. Here's my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Swarm Profile</title>
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="/js/script.js"></script>
</body>
</html>
And my Node.js server file:
var http = require('http');
var fs = require('fs');
const hostname = '127.0.0.1';
const port = 9000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
fs.createReadStream("./index.html").pipe(res);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
What should I use to be able to access the script.js file?
There are many static file handler modules already in node, take a look at:
Node static modules
Most popular are: Node-Paperboy and Node-Static
Using node static is as simple as:
var static = require('node-static');
var file = new(static.Server)('./public');
require('http').createServer(function (request, response) {
request.addListener('end', function () {
file.serve(request, response);
});
}).listen(8080);
Related
I'm trying to make a website using HTML/CSS/JavaScript on the client-side, and use Node.js and SQLite on the server-side.
Below is the code I wrote in 'app.js' which is my server page.
var express = require('express');
var app = express();
var fs = require('fs');
const sqlite3 = require('sqlite3');
const sqlite = require('sqlite');
app.use(express.static('public'))
async function getDBConnection(){
const db = await sqlite.open({
filename: "author.db",
driver: sqlite3.Database
});
return db;
}
app.get('/', async function(req, res){
let db = await getDBConnection();
let authors = await db.all("SELECT * from author");
await db.close();
})
var port = 3000;
app.listen(port, function(){
console.log('server on! http://localhost:' + port);
});
I'm trying to extract the data from the author.db, and use the extracted data in a separate javascript file, which is the 'script.js' file. Is there any way for me to do this? I've tried putting two script tags in my index.html file, but an error appears indicating that the server cannot locate the app.js file.
Below is my code for index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Main Page</title>
<link rel = "stylesheet" type = "text/css" href = "main.css">
</head>
<body id = "i_body">
<div class = "fpage">
<main>
</main>
</div>
<script src = "app.js></script>
<script src = "./script.js"></script>
</body>
</html>
So your app.js is your node server. It runs as a backend server - you don't include it as a reference on your front end. Your front-end has to make a request to the backend server (usually using a library like axios) which will fetch the data that the backend provides you. So in your get '/' section you will want to return a json response with your records. Then on your client side, use a library like axios to fetch the data and then use it how you like.
Edit:
Your server code can look something like this:
var express = require('express');
var app = express();
var fs = require('fs');
const sqlite3 = require('sqlite3');
const sqlite = require('sqlite');
app.use(express.static('public'))
async function getDBConnection(){
const db = await sqlite.open({
filename: "author.db",
driver: sqlite3.Database
});
return db;
}
app.get('/api/authors', async function(req, res){
let db = await getDBConnection();
let authors = await db.all("SELECT * from author");
await db.close();
return res.json(authors)
})
var port = 3000;
app.listen(port, function(){
console.log('server on! http://localhost:' + port);
});
Notice that you are now serving the json off an api endpoint - in this case /api/authors although this can be anything.
Put your client files in the public folder - so index.html and script.js should be there. Your index.html file should look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Main Page</title>
<link rel = "stylesheet" type = "text/css" href = "main.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body id = "i_body">
<div class = "fpage">
<main>
</main>
</div>
<script src = "./script.js"></script>
</body>
</html>
Notice that I have included the CDN for the axios library, and removed the reference to the node part in your client. Your script.js can look like this:
axios.get('http://localhost:3000/api/authors').then((res) => {
console.log(res.data)
})
Here you can see I'm using the axios library to call the backend with the endpoint that I mentioned before /api/authors. It gets the json as res.data. At that point you can do whatever you want to it. Hope that helps!
I'm currently trying to make a game using Node.js, Express, and Socket.io. However, when I attempt to run it locally I get a 404 error stating that my javascript files can't be found. My file structure looks like this:
root
| game
| | game.html
| | game.js
| index.js
And my code looks like this:
index.js
//Dependencies
var express = require('express'); //Pulls in Express framework
var http = require('http') //Pulls in http module
var socketio = require('socket.io'); //Pulls in Socket.io framework
//Instance Declarations
var app = express(); //Creates an Express instance
var server = http.createServer(app); //Creates an http server using the Express framework
var port_to_listen = process.env.PORT || 3000; //Specifies which port to listen on
var socket = socketio(http); //Creates Socket.io instance related to the server just created
//Default page displayed, always sent to index.html
app.get('/', (req, res) => {
res.sendFile(__dirname + '/game/game.html');
});
//Tells the server to listen for any incoming inconnections
server.listen(port_to_listen, () => {
console.log(`listening on ${port_to_listen}`);
});
socket.on('connection', function(client) {
console.log('Connection made')
});
//Testing to ensure socketio works
setInterval(function() {
socket.sockets.emit('message', 'hi!');
}, 1000);
game.js
var socket = io();
socket.on('message', function(data) {
console.log(data);
});
game.html
<html>
<head>
<title>A Multiplayer Game</title>
<style>
canvas {
width: 800px;
height: 600px;
border: 5px solid black;
}
</style>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script type = "text/javascript" src="game.js"></script>
</html>
The error messages look like this:
What should I do to fix these errors?
Edit:
These errors also still persist when I change the src path for game.js to
<script type = "text/javascript" src="/game/game.js"></script>
You have only one route that serves files:
app.get('/', (req, res) => {
res.sendFile(__dirname + '/game/game.html');
});
The rest of the files (your css, js, etc.) are not served automatically
You need to create route(s) for that, like explained here Serving static files in Express
I have following code for running server
server.js :
var http= require('http');
var fs= require('fs');
var file= fs.readFile("./public/index.html", function(error,html) {
if (error) {
throw error;
} else {
var server= http.createServer(function(req,rspn) {
rspn.writeHead(200,{"Content-Type":"text/html"});
rspn.write(html);
rspn.end();
});
server.listen(8000);
}
});
And my index.html and client.js files are in public folder. My index.html file is following
<!DOCTYPE html>
<html>
<head>
<title> WEBCAM </title>
</head>
<body>
<div>
<button id='request'>Request Camera</button>
<script type="text/javascript" src="client.js"></script>
</body>
</html>
And I have some code written in client.js. Now after running server.js if I open localhost:8000 in browser then I saw in console that in client.js same index.html code is getting copied. It is not reading the content of client.js
What is wrong I am doing here?
Check if this solve your problem:
var http= require('http');
var fs= require('fs');
var server= http.createServer(function(req,rspn) {
rspn.writeHead(200,{"Content-Type":"text/html"});
fs.createReadStream("./public/index.html").pipe(rspn)
}).listen(8000);
}
});
I want to run index.html file (in which external js file client.js is included) through nodejs
Here is my index.html code:
<!DOCTYPE html>
<html>
<head>
<title> WEBCAM </title>
</head>
<body>
<div>
<button id='request'>Request Camera</button>
<script type="text/javascript" src="client.js"></script>
</body>
</html>
and here is my server code which i am making to run this file through nodejs
var http= require('http');
var fs= require('fs');
var file= fs.readFile("./public/index.html", function(error,html) {
if (error) {
throw error;
} else {
var server= http.createServer(function(req,rspn) {
rspn.writeHead(200,{"Content-Type":"text/html"});
rspn.write(html);
rspn.end();
});
server.listen(8000);
}
});
If i copy the external js file directly into html file and run it through nodejs , then it is working properly but not if i make the js file as an external file.
My external file(client.js) is following -
function requestVideo() {
if (hasGetUserMedia()) {
navigator.getUserMedia({video: true,audio:false}, function(localMediaStream) {
reqBtn.style.display = 'none';
video.src = window.URL.createObjectURL(localMediaStream);
startBtn.removeAttribute('disabled');
},errorCallback); }
else{
alert("getUserMedia() is not supported in your system");
}
}
I you want to serve files like html or js files you can create a static file server as folows:
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
var filePath = '.' + request.url;
var extname = path.extname(filePath);
var contentType = 'text/html';
if(extname == '.js'){
contentType = 'text/javascript';
}
fs.readFile(filePath, function(error, content) {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
});
}).listen(8000);
so as said above, i run the html file only and i'm able to see the pictures, but when i run the file via node it sends me a 404 error on the file i used.
<html>
<body>
<img src="aaa.jpg" />
<script src="/socket.io/socket.io.js">
</script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
</script>
</body>
</html>
and the node code
var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});
how can i stop this from happening?
To serve static files such as images and scripts, you need to include a middleware that serves static files. Put all your static files inside of a public directory and serve them like this.
var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
// Serve static files
app.use(express.static(__dirname + '/public'));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
console.log("Server Open");
});