How to sendFile in express using req.params and join method? - node.js

I'm creating routes in express.js using route parameters. I want a url example.com/case/firstCase with firstCase being a parameter.
However, I don't know how to use sendFile with params. What I'm trying to do is to append .html but I think it's not working since the method join add / between each element separated by comma. In other words, the path would be views/statics/case/firstCase/.html
Here is my code in server.js.
const express = require('express')
const app = express()
const path = require('path')
// no need to use app.use(app.router) because of that update
// function signature express.static(root, [options])
app.use(express.static('public'));
// mount root to views/statics
app.use('/', express.static('views/statics'));
const PORT = process.env.PORT || 3000;
app.listen(PORT,() => {
console.log(`Server is listening on port ${PORT}`)
});
app.get('/case',(req,res,next)=> {
res.sendFile('case.html', { root: path.join( __dirname, 'views/statics')})
})
app.get('/case/:case',(req, res)=>{
res.sendFile(path.join(__dirname, 'views/statics/case', req.params.case + '.html'));
}))

As above discussion your are not use view engine.
Add view engine like
Pug link
Ejs link

Related

How to send css files with express js

I am having a hard time sending css files with express. The way my project is structured is I have a src folder and inside the src folder is the app.js for the express code as well as another folder titled "public". Inside of this public folder I have an experience.html page as well as an experience.css page. I can only get the html to render on the page and cannot get the css styling to show up. Attached is my code for the app.js page.
const express = require('express');
const app = express ();
const port = process.env.Port || 3000;
app.get('/experience', (req, res) => {
res.sendFile(__dirname+'/public/experience.html');
})
app.use(express.static('/public/experience.css'))
app.listen(port);
Just using middleware is enough, you don't need dedicated get routes to the files unless you want to mask some of the filenames.
This should work for your case
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000);
You can access them on http://localhost:3000/experience.html, http://localhost:3000/experience.css
You can use the Express static middleware with the path to the public folder.
Once you do that, you can expose a route to the files (or) you can access at localhost:9900
//Import modules
const express = require("express");
const path = require("path");
// Define PORT for HTTP Server
const PORT = 9900;
// Initialize Express
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.listen(PORT, (err) => {
console.log(`Your dog server is up and running!`);
});

Express.js route almost everything to one request

I want to map all the requests that don't point to static files to my index.html and let javascript do the routing. But if I use the rules below all my requests (including the scripts and styles) hit the * rule.
const express = require("express");
var app = express();
app.get("*", function (request, response) {
response.sendFile(path.join(__dirname, "/index.html"));
});
app.use("/scripts/*", express.static("scripts"));
app.use("/styles/*", express.static("styles"));
app.use("/views/*", express.static("views"));
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log("Server is running, port: " + port);
});
I've also tried the reverse order.
Just to clarify here are some examples of what the expected behavior is:
/scripts/index.js => /scripts/index.js
/views/app.html => /views/app.html
/anything/here => /index.html
/ => /index.html
/a/lot/of/stuff => /index.html
I want to upload this to heroku and I don't want to use that many free credits. So I want to have all the routing and stuff on the JS to save up on computation on the server.
app.use('/scripts', express.static('scripts'));
app.use('/styles', express.static('styles'));
app.use('/views', express.static('views'));
app.get('/', function (request, response) {
response.sendFile(express.static(path.join(__dirname, 'index.html'));
});
Try to use the code in this manner and I really hope this will work for you
Try this code.
Put all your files inside public folder (including index.html and other folders like script, styles, views)
const express = require('express')
const path = require('path')
const app = express()
const PORT = process.env.PORT || 3000
app.use(express.static(path.join(__dirname, '/public')))
app.get('*', (req, res) => {
res.redirect('/')
})
app.listen(PORT, () => console.log(`Server is running, port: ${PORT}`)
Your code will start working if you shift app.use functions to the top of your code

Why can't I view my home page like I can on a local host

I am trying to upload my website on digital ocean using express, node and react. I can view my website on localhost:3000 but when I run nodemon on the publicip:3000 all I see is /root/website/src/index.html displayed on the page. Here is the server.js file
const express = require('express');
const app = express();
//Set port
const PORT = process.env.PORT || 3000;
//Import path
const path = require('path');
//Static files
app.use(express.static('build'));
//Server will use index.html
app.get('/*', (req, res) => {
res.send(path.join(__dirname + '/src/index.html'));
});
app.listen(PORT, () => {
console.log('Listening on port ${PORT}');
});
If you are using res.send() then it will send the path of the file. And path.join should contain the values separated with commas as it takes the values as string array.
Try this
If you want the actual file to send.
res.sendFile(path.join(__dirname ,"src/index.html"));

Capture all http requests with node/express

I am looking to capture all of the data from any request (images, fonts, css, js, etc) on my website so that I can capture the file details, specifically the file name and file size. I have found almost an identical question/solution:
Node.js : How to do something on all HTTP requests in Express?
But the solution appears to be deprecated with Express v4. Is there a simple solution to do this? As another approach I have tried the below solution with no luck:
var express = require("express");
var path = require("path");
var port = process.env.PORT || 3000;
var app = express();
var publicPath = path.resolve(__dirname, "public");
app.use(express.static(publicPath));
app.get("/", function(req, res){
// I want to listen to all requests coming from index.html
res.send("index.html");
});
app.all("*", function(){
// can't get requests
})
app.listen(port, function(){
console.log(`server listening on port ${port}`);
});
Also I am not looking to do this from Fiddler/Charles because I am looking to display this data on my site.
Express routes are predicated on order. Notice the answer that you linked in your question has the middleware defined, and used before all other routes.
Secondly you're trying to implement something that requires middleware, not a wildcard route. The pattern in link you provided in your question is not deprecated according to their docs.
app.use(function (req, res, next) {
// do something with the request
req.foo = 'testing'
next(); // MUST call this or the routes will not be hit
});
app.get('/', function(req, res){
if (req.foo === 'testing') {
console.log('works');
}
res.send("index.html");
});

Express SSL redirect not working for root /

I use a wildcard match at the end of my Express route declarations to test if the connection is not HTTPS and if not, to redirect to the HTTPS version of the URI.
This works for everything except root, i.e., www.domain.com. This is a bit of a problem because domain.com serves a SPA.
app.get('*', function (req, res) {
if (req.headers['X-forwarded-proto'] != 'https') {
res.redirect('https://domain.com/#' + url_path);
}
else {
res.redirect('/#' + url_path);
}
});
I noticed that this chunk of code does not even get called when the URL is the root domain. I think this might be because I also declare:
app.use(express.static(path.join(application_root, 'public')));
This is necessary for the SPA to serve all of the assets. When I remove this line, my route handler is now called for the root domain, but my home page now infinitely redirects.
I had to create a custom route to server my SPA file, rename index.html so that Express would not try to serve it instead of my route.
To anyone who might still be struggeling with this, I had the same problem deploying my React-Express App on Heroku. I used a middleware: "heroku-ssl-redirect". The solution for me was to put this middleware up in the hierarchy (now its the first middleware I am applying):
var sslRedirect = require("heroku-ssl-redirect");
const express = require('express');
const path = require('path');
const e = require('express');
const app = express();
app.use(sslRedirect());
// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
// Handles any requests that don't match the ones above
app.get('*', (req, res) =>{
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port);
console.log('App is listening on port ' + port);

Resources