Using Express.js, how can I send a file on any request? - node.js

I'm trying to send index.html on any get request.
Code:
import express from 'express';
import path from 'path';
const app = express();
app.use(express.static(path.join(__dirname, '..', 'dist')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, '..', 'dist', 'index.html'));
res.end();
});
app.listen(8000, () => console.log('Server started on port 8000'));

change your
app.use(express.static(path.join(__dirname, '..', 'dist')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, '..', 'dist', 'index.html'));
res.end();
});
to
app.use(express.static(path.join(__dirname, '..', 'dist')));
app.get('*', function (req, res) {
res.sendFile('index.html', {root: path.join(__dirname, '..', 'dist')});
res.end();
});

A nice technique you can use here is to store the html page in the ram so your system doesn't have to read the file every time a request is made. I suggest you to use the fs library. Try the following.
import express from 'express';
const fs = require('fs')
const app = express();
var indexPage = fs.readFileSync(__dirname + '/PATH_TO/index.html', 'utf8')
app.get('*', function (req, res) {
return res.send(indexPage)
})
app.listen(8000, () => console.log('Server started on port 8000'));
With your current solution you try to read the file for every request. By doing the above you will save a lot of CPU power and provide a much faster result.

Related

Node.js: res.redirect function is not working

res.redirect function is used to redirect the user to another page by clicking a button. But the function's not working. Please find the code below.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/failure", function (req, res) {
res.redirect("/");
});
app.post("/success", function(req, res) {
res.redirect("/");
});
app.listen(process.env.PORT || 3000, function () {
console.log("The server is running at port 3000");
});
Try moving
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
below your other routes and try calling again
Try changing app.post to app.get:
app.get("/success", function(req, res) {
res.redirect("/");
});

Remove filename from URL with Express

When I host my front-end on Nodejs, I use app.use(express.static(path.join(__dirname, "public")));. However, this makes me put the name of the HTML file at the end of the URL; for example, localhost:3000/index.html.
How would I make it show the front-end at the base URL, in this case, "localhost:3000/". I have attached a part of my Nodejs code. I would appreciate any help and thank you in advance.
var path = require('path');
var express = require('express');
const app = express();
const port = process.env.PORT || '3000';
app.use(express.json());
app.use((req, res, next) => {
console.log(req.path);
next();
});
app.use(express.static(path.join(__dirname, "public")));
app.listen(port, () => console.log("Server is ready"));
You can use a route path and sendFile method:
app.get("/", function(req,res) {
res.sendFile("index.html", {root: path.join(__dirname, "public")})
})
More details here
This is how you would do.
//for static files like css and html
app.use('/static', express.static(path.resolve(__dirname, path to css and js)));
app.get('/*', (req, res)=>{
res.sendFile(path.join(__dirname, 'path to your html file'))
})

How to pass data from Node.JS to React build

Suppose this is my server.js:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(9000);
And this is the React component which is going to received the data from the server.js:
import * as React from 'react';
export const DisplayName = (props: any) = {
return (
<p>Hi there: {props.match.params.data}</p>
)
};
So how do I pass/post the data to this component from Server.js via URL: i.e. http://example.com/displayName/Phil, http://example.com/displayName/Jake...
Is it possible to do something like these?
app.get('/displayName/:data', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
// or
app.post('/displayName/:data', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

Express server not listening to get url request and returning to / always

I have the following express server setup:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function (req, res) {
console.log('/*');
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.get('/test', function (req, res) {
console.log('test');
//res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(9000);
Everytime I hit localhost:9000/test, it still take to the route '/'.
I tried placing the app.get code before the static declaration but I don't think that really makes any difference. Any idea why this is happening?
Your existing code is fine. It should work.
I believe you had your index route as app.get('/*', function (req, res){ instead of app.get('/', function (req, res) { before and that's why it was capturing all requests.
In the /test route handler you have to terminate the request-response cycle by using res.end(), something like this:
app.get('/test', function (req, res) {
console.log('test');
res.end();
});
Otherwise the page will never refresh showing the first page (route /)
Hope this helps

express.static doesn't point to the right path

I get a problem every time I try to reach /about
This code works and all is fine
var express = require('express');
var path = require('path');
var app = express(); // define our app using express
var port = process.env.PORT || 3000; // set our port
console.log(path.join(__dirname, 'public'));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'public')+'/index.html');
})
.get('/about', function(req, res) {
console.log(__dirname);
res.sendFile(path.join(__dirname, 'public')+'/about.html');
})
.get('/signIn', function(req, res) {
res.sendFile(path.join(__dirname, 'public')+'/signIn.html');
});
app.listen(port);
console.log('Magic happens on port ' + port);
but when I try to place the public folder in express.static I get an error
"Error: ENOENT: no such file or directory, stat 'C:\about.html'
at Error (native)"
var port = process.env.PORT || 3000; // set our port
app.use(express.static(path.join(__dirname, 'public')));
console.log(path.join(__dirname, 'public'));
app.get('/', function(req, res) {
res.sendFile('/index.html');
})
.get('/about', function(req, res) {
console.log(__dirname);
res.sendFile('/about.html');
})
.get('/signIn', function(req, res) {
res.sendFile('/signIn.html');
});
app.listen(port);
console.log('Magic happens on port ' + port);

Resources