Express in NodeJS: URL param breaks routing - javascript

I'm trying to use express to serve my index.html, its dependancies as well as handle url params. For some reason, adding a URL param seems to break the pathing.
My basic nodeJS webapp has the following folder structure:
|- server.js (nodeJS server code)
|- public (dir)
| - app.js (app logic dependancy)
| - index.html (base HTML file to be served from server.js)
index.html is importing app.js as follows:
<script type="text/javascript" src="app.js"></script>
My express routes are as follows:
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/:country', (req, res) => {
res.sendFile(__dirname + '/index.html', {country:req.params.country});
}
I want the app to be served even when the country param is used.
However, when I add the URL param route, the above route stops working because express looks for index.html in the folder root, resulting in a 404.
Eg: http://localhost:3000/usa
Error: ENOENT: no such file or directory, stat '/Users/john/Projects/TestApp/index.html'

However, when I add the URL param route, the above route stops working because express looks for index.html in the folder root, resulting in a 404. Eg: http://localhost:3000/usa
Error: ENOENT: no such file or directory, stat '/Users/john/Projects/TestApp/index.html'
You should add public to the directory path, then.
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
Or, to work cross-platform:
const path = require("path")
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"))
})

Related

How to serve folder in 'public' with express

I am trying to serve the login page in my public folder in express, so far i have been unable to do so. I tried to work the path but I don't know why it does not work. What I want to have is that I can have more code in the callback but because of the way it is now I can do that, when I try to make the callback a full function it won't work either.
My folder structure
- root
- server
- server.js
- public
- login
- index.html
const express = require('express');
const app = express();
const path = require('path');
app.listen(4000);
console.log('server started\n');
app.get('/', () => app.use(express.static(__dirname + '/public/login')));
// what i want to have
app.get('/', () => {
// serve file
});
You should mount the static file serving directly when the server starts, not after the first request arrives so this line:
app.get('/', () => app.use(express.static(__dirname + '/public/login')));
has to be:
app.use(express.static(__dirname + '/../public/login'));
You also have to go up one folder as the code is started in the /server/ directory, which can be done with /../.
If you only want to server the index.html from public folder instead of all files in there, what you can do is
app.get('/', (req, res) => res.sendFile('index.html', { root: __dirname + '/../public/login'));

Different Path for Serving Static HTML files in Express

Just a quick question. Say I have 2 different static HTML files that I want to serve in Express, index.html and contact.html. I've been fiddling around and I currently use this barebone Express code to serve them:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static('public'))
app.get('/', function (req, res) {
res.sendFile('/index.html');
});
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/public/contact.html');
});
app.listen(3000, function () {
console.log('runnning on port 3000')
});
Question is, I tried to serve contact.html using
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
but it always resort to the root directory instead of the public directory. OTOH, I can server index.html just fine without having to explicitly adding /public in the response.
Can anybody point me what's the cause for that?
Thanks.
For the given file structure:
yourapp
|-- contact.html
|-- index.html
`-- server.js
The following code would work just fine:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
Assuming both index.html and contact.html have read access.
Remember, sendFile requires an absolute path and __dirname refers to your app directory. Make sure you give references according to your file location.

Nodes Express App.Route Path Confuse the Other folder

I am use Nodes.js Express to do my route.
For the normal one... localhost:8080/Order its go work wells. But i am try to use use get method with the ID method localhost:8080/Order/ID-12345 and continue to ViewOrder.html to perform the function. But its shown out some error.
Error
Failed to load resource: the server responded with a status of 404 (Not Found)
localhost:1337/Orders/img/p7.jpg
Failed to load resource: the server responded with a status of 404 (Not Found)
localhost:1337/Orders/css/bootstrap.min.css
and etc..
Instead of
localhost:1337/css/bootstrap.min.css
// Index Page
app.get('/Order', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/Orders/:item', function (req, res) {
res.sendFile(__dirname + '/ViewOrder.html');
});
Order and Orders is not a directory. I used part of the route
code
Error
In your file server.js (the file that start your application) have you set the static dirname?
For me this resolve your problem:
var app = express();
app.use('/Orders', express.static(__dirname));
This setting set up the statics file for your project.
For more information this is helpfull express static resources
Yep! You need to specify your static folders in order serve static files.
So in your case i would do this to your server.js ;)
var express = require('express'),
app = express(),
http = require('http').Server(app);
const ipaddress = "127.0.0.1";
const port = 1337;
app.use(express.static(__dirname + '/Order'));
app.use(express.static(__dirname + '/Orders'));
app.get('/', function (req, res) {
res.sendFile('index.html', {"root": __dirname});
});
app.get('/:id', function (req, res) {
var param=req.params.id;/// hu! gotcha little param
res.sendFile('Orders/index.html', {"root": __dirname});
});
http.listen(port, ipaddress, function () {
console.log((new Date()) + ' Server is listening on port' + port);
});
UPDATE - according to comment (Actually Order is not a directory, I use Order as route to linked to directory – Brian)
Pretend a public folder would be your root/static this would be my second attempt
app.use(express.static(__dirname + '/public'));
app.get('/Order', function (req, res) {
res.sendFile('public/index.html', {"root": __dirname});
});
app.get('/Orders/:item', function (req, res) {
res.sendFile('public/ViewOrder.html', {"root": __dirname});
});
attention
i had to modify static requests
<link rel="stylesheet" type="text/css" href="style.css">
- TO -
<link rel="stylesheet" type="text/css" href="/style.css">
If you want your html pages to load css/js assets your need to serve them as static file ( documentation : http://expressjs.com/en/starter/static-files.html )
The image and bootstrap file can't be loaded because you haven't specified a static folder.
app.use('/media', express.static(__dirname + '/media'));
Using this, all files in the media folder can be requested by refering to them with /media/img/p7.jpg.
You may as well change the request path:
app.use('/static', express.static(__dirname + '/your/real/path'));
Thus you can refer to them like /static/img/p7.jpg.

Scotch-io/node-todo app

How is the index.html (frontend Angular) getting called exactly?
In the tutorial, it was said that by having one of the following routes in route.js, frontend is getting called
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
----------or-------------------
app.get('*', function(req, res) {
res.sendfile('__dirname + '/public/index.html');
});
But even after removing that route, index.html is getting opened (or) If I rename index.html as index1.html at route and html file it is showing error.
Have you created a file index1.html in public folder? If yes, Use
res.sendfile('public/index1.html');
OR
var path = require('path');
res.sendFile(path.join(__dirname, '../public', 'index1.html'));
to render index1.html.
Note : sendfile is deprecated.

express - Angular2 Error: ENOENT: no such file or directory upon refresh

I have a public folder in which I put an angular2 app. Now I am trying to setup an express server with a catchall route that always returns index.html. To be clear - according to this question I need to map all of my routes to index.html.
If I access the base server URL (localhost:10001), everything works as expected. But when I go to a route(let's say localhost:10001/landing), and refresh the page, I get the following error:
Error: ENOENT: no such file or directory, stat
'/Users/shooshte/express-test/index.html' at Error (native)
This is my server configuration:
var express = require('express');
var static = require('serve-static');
var server = express();
// middleware
server.use(express.static(__dirname + '/public'));
// routes
server.use('*', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
var port = 10001;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
What am I doing wrong?
You're missing the public directory in the path to index.html:
res.sendFile(__dirname + '/public/index.html');
i think you don't have your index.html in either public or your root folder /Users/shooshte/express-test/
this is the only resion you are getting this error

Categories