I am an express newbie, and I am trying to get a static HTML page to read details from a file in Express.
Initially I had a static HTML page where users could register where they were based on a particular day (as we are now rather flexible with working arrangements). However, it became apparent that I needed to store the current situation somewhere each time someone updated their details (and retrieve it when someone else signs on), so I did some investigating and came up with Node and Express.
I have an HTML file in the public directory, and it links to a JS file where I want to do a "fs" read.
app.js
app.use(express.static(path.join(__dirname, 'public')));
var steveRouter = require('./routes/steve');
app.use('/steve', steveRouter);
routes/steve.js
var express = require('express');
var path = require('path');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.sendFile(path.resolve(__dirname, '../public', 'steve.html'))
});
module.exports = router;
public/steve.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello World : title</title>
<script src="steve.js"></script>
</head>
<body onLoad="loadUp()">
<h3>small-ish heading</h3>
</body>
</html>
public/steveHtml.js
const fs = require('fs');
function loadUp() {
alert("Ciao");
let rawdata = fs.readFileSync('student.json');
let student = JSON.parse(rawdata);
console.log(student);
alert(student.name);
}
The server starts ok, but the browser shows the message "Uncaught ReferenceError: require is not defined at steveHtml.js:1"
This is probably the wrong way of doing it, but I would love to know :
how do I get the "called" JS file to recognise the require command?
is there a better/simpler/easier way of accomplishing what I want?
Related
I'm stuck. I thought my goal was going to be straight forward but I appear to be missing some key piece.
I'm trying to build a website that can accept a JSON file from an end user. Once the file has been provided I want to combine that data with data from a web-resource and then take the resulting flattened JSON and write it to a database table.
The first prototype of the project was built in a single HTML page with some JavaScript and I succeeded in getting the output the way I wanted it to look.
Then I tried to convert it to a node.js server so I could use an API to write the resulting JSON to the SQL server.
While the problem with which I am asking for help does not involve those steps I just wanted to share that there are some complexities of async that are possibly muddying things.
I've tried creating an HTML page that accepts a file and using express tried to capture that file, but I can't seem to figure out the right combination of middleware and other code to get the JSON file loaded into an object so I can feed it to my existing function to manipulate it and then subsequently feed it to a function to write it to SQL using a stored procedure.
So here's what I've got for my index.js
const express = require("express");
const app = express();
const fileUpload = require('express-fileupload');
const bodyParser = require("body-parser");
const path = require("path");
app.use(express.urlencoded({
extended: false
}));
app.use(express.json());
app.use(fileUpload());
app.post('/upload', function(req, res) {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
let jsonFile = req.body.sampleFile;
console.log(jsonFile);
let parsed = JSON.parse(jsonFile);
console.log
res.send("blank page");
});
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/minimalIndex.html'));
});
const webserver = app.listen(5000, function() {
console.log('Express web server is running..');
});
and the HTML that it uses is this
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Static Index.html</title>
</head>
<body>
<form ref='uploadForm' id='uploadForm' action='/upload' method='post' encType="multipart/form-data">
<input type="file" name="sampleFile" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>
The console.log shows undefined.
The JSON Parse fails because of an invalid JSON string.
I've succeeded at saving the file locally but that seems unnecessary.
Can someone please tell me what it is I am missing?
Everything is correct apart from the way you are trying to fetch the files. You are trying it from body while it should be from files. Something like this
let jsonFile = req.files.sampleFile;
let parsed = JSON.parse(jsonFile.data.toString("utf-8"));
Hope it helps
I am beginner to node and express. In my current application the page is displaying using this code :
var app = express();
app.use(serveStatic('static', {'index': ['index.html']}));
and in static folder, there are there files:
css, index and a js file
Listening to 3000 port it is working normally.
But what if I want to access URL like this :
localhost:3000/name=someName
I want to use this name parameter in my js file which is available in static folder.
or suggest any other routing method to do that?
If you want to get the query parameters in your .js file it can be done. So the code would look like this:
Server (index.js)
"use strict";
var express = require("express");
var serveStatic = require('serve-static');
var app = express();
app.use(serveStatic('static', {'index': ['index.html']}));
app.listen(3000);
console.log("Static express server started");
HTML (/static/index.html)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body onLoad="readParameters()">
<div>
<h3 id="1" >Loading..</h3>
</div>
</body>
</html>
Client side JavaScript (/static/test.js)
var readParameters = function()
{
console.log('Getting parameters..');
let params = (new URL(location)).searchParams;
console.log('Query parameters: ', params.toString());
var html = 'Query parameters: ';
for (let p of params) {
html += "<br/>" + p.toString();
}
$("#1").html(html);
}
Then you can test by entering:
http://localhost:3000/?test=value
Into your browser.
You should see:
Query parameters: test=value
on the index page.
The code tree should look like this:
root
¦ index.js
¦
+---static
index.html
test.js
3 Files:
/index.js (Node server side code)
/static/index.html (HTML)
/static/test.js (Test JavaScript file)
You can defined route like below,
router.get('/name=:id', function(req, res, next) {res.render('index', { title: req.params.id});});
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. This captured values we can access with 'req.params' object. for reference https://expressjs.com/en/guide/routing.html
I have created basic node/express server
var express = require('express');
var app = express();
var path = require('path')
var port = 8080;
app.use("/styles", express.static('../public/styles'));
app.get('/' , function( req , res ){
console.log(__dirname)
res.sendFile(path.join(__dirname,'../public/html/index.html'))
})
app.listen(port)
structure of project is simple
app
public
html
index.html
styles
javascripts
routes
server.js
html file looks very simple
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../styles/index.css">
<title> Hello world!</title>
</head>
<body>
</body>
</html>
yet it still complains
GET http://localhost:8080/index.css 404 (Not Found)
Yet my paths should be correct , i looked up this problem and every answer is about using
app.use("/styles", express.static('../public/styles'));
so browser know how to redirect when looking for a stylesheets. Which does not work for me.
Could anybody help with this common problem?
Thanks!
Not clear what your project structure is. It's more common to have app.js in your project directory contain the basic express server and if you have complicated routing, do that in routes/server.js
So you could change your project structure:
app.js (main file)
public
index.html
styles
index.css
javascripts
routes
server.js --not needed?
If that's the case, change app.js to:
var express = require('express');
var app = express();
var port = 8080;
//use static folder public to serve everything up
app.use(express.static('./public/'));
app.listen(port)
In index.html, to include index.css:
<link rel="stylesheet" href="/styles/index.css" >
Following are the structure of my application
Inside prototype.js file i have following code:
(function(exports) {
exports.foo = function() {
return 'bar';
};
})((typeof process === 'undefined' || !process.versions) ? window.common = window.common || {} : exports);
app.js contains
var express = require('express'),app = express(),server = require('http').createServer(app),io = require('socket.io').listen(server),port = 3000,path = require('path');
var common = require('common/prototype');
console.log(common.foo());
// listening to port...
server.listen(port);
//Object to save clients data
var users = [];
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.sendfile('/public/index.html');
});
index.html contains
<!doctype html>
<html lang="en">
<head>
<title>Socket.io Demo</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="/common/prototype.js"></script>
<script>
alert(window.common.foo()); //This line will gives me an error TypeError: window.common is undefined
</script>
</body>
</html>
Now i would like to print
Hello, I am bar from server and client as well.
Now i am able to print from server side using following line
var common = require('common/prototype');
console.log(common.foo());
But could not able to show alert on client side. could you please help me to find the root cause for the issue.
The root cause is that when you do <script src="/common/prototype.js"></script> in your HTML the file won't be fetched because the Express static middleware is only looking for files under your public folder.
A quick way to test this is to copy your prototype.js to your javascript folder inside public. Then update your script tag to reference the file as follows <script src="/javascripts/prototype.js"></script>
The thing to remember is that the JavaScript files that live under node_modules are not automatically available to the browser.
I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.
app.js
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');
var PORT = 8080;
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('board.ejs', {
title: "anything I want",
taco: "hello world",
something: "foo bar",
layout: false
});
});
app.listen(PORT);
console.log("Server working");
The ejs file is in a directory views/board.ejs
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='../styles/style.css' />
</head>
<body >
<h1> <%= taco %> </h1>
<p> <%= something %> </p>
</body>
</html>
and style.css is in a styles/style.css directory relative to app.js
p {
color:red;
}
I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.
Declare a static directory:
app.use(express.static(__dirname + '/public'));
<link rel='stylesheet' href='/style.css' />
in app.js:
you must first declare static directory
app.use("/styles",express.static(__dirname + "/styles"));
in ejs file :
<link rel='stylesheet' href='/styles/style.css' />
Recently I was working with this same thing and my CSS was not working. Finally, I get the trick. My static path was like below,
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const staticDirectory = express.static(publicDirectoryPath);
app.use(staticDirectory);
and my folder structure was like
The trick is that express access only defined static path, in my case CSS was outside of public so it was not working and suddenly I move CSS folder inside my public folder and that's it. Works beautifully.
Above example was for only one static path. For multiple static path you can use the code in the below
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const cssDirectoryPath = path.join(__dirname, '../src/css');
const staticDirectory = express.static(publicDirectoryPath);
const cssDirectory = express.static(cssDirectoryPath);
app.use(staticDirectory);
app.use('/css/',cssDirectory);
And my generic HTML file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<h1>this is index page</h1>
</body>
</html>
To set the entry point for your application dependancies like css, img etc add below line into your server.js (or which ever being used).
app.use(express.static(__dirname + '/'))
This tells to get css files from current directory where server.js is present. Accordingly you can define relative path of css in html file.
With Express 4, you can easily set this up by using the following within your app.js file.
app.use('/static', express.static(path.join(__dirname,'pub')));
Place this early in your file, after you created your require constants, and declared your express app.
Its declaring a static directory, with the help of the path object, allowing you to have a place where all of your front-end resources are available. It's also giving it a virtual directory name (/static) that can be used on the front of the site, instead of the physical name you see within your project (/pub).
In your template you can do something like this in your head
<link rel="stylesheet" href="/static/css_bundle.css"/>