Remove filename from URL with Express - node.js

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'))
})

Related

How do i stop access to my index.html file using node and ejs

How do i stop access to index .html file and let people sign up on home.ejs, i was building a static website but now making a web app and want people to sign up.
i commented out the index section but still the index gets on first instead of home.
I want people to sign up first and then use the app
This is my code.
//jshint esversion: 6
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
/* app.get("/", function(req, res){
res.sendFile(path.join(__dirname, "public", "index.html"));
}); */
app.get("/home", function(req, res){
res.render("home")
})
app.listen(3000);
console.log('now the server is running')
App using static assets from public which includes your index.html file.
You can remove index.html from a static source
app.get("/", function(req, res){
res.sendFile(path.join(__dirname, "views", "index.html"));
});
Or you can give a base path to static folder.
app.use('/public' ,express.static(path.join(__dirname, 'public')));

How can I fix this cors error with cors module

I installed cors module and coded like below.
var express = require('express'),
favicon = require('serve-favicon'),
cors = require('cors');
var app = express();
if (app.get('env') === 'development') {
app.locals.pretty = true;
}
app.set('view engine', 'pug');
app.set('views', './views');
app.use(express.static(__dirname + '/public'));
app.use(favicon(__dirname + '/public/img/logo.ico'));
app.use(cors());
app.get('/', (req, res) => {
res.render('view');
});
app.listen(80, () => {
console.log('Server started on port 80');
});
After this I turned on server and tried to access files on server by this code.
$.getJSON('https://server.domain/global.json', data => {
console.log(data);
});
But It makes error.
I can access to js files but not json file.
What's the problem?
[+Edit]
I can get js files by
$.getScript('~/js/file.js');
But not by
$.get('~/js/file.js');
do you get the error after trying this:
app.get('/', cors(), (req, res) => {
res.render('view');
});
and
$.getJSON('https://server.domain/global.json', cors(), data => {
console.log(data);
});
Server in express don't allow you to access files directly.
if you want it to enable access files directly . you have to do it like this
app.use(express.static('public'))
now you can access files in public folder directly like
if there is file data.json in public, you can access it by localhost:3000/data.json.
Hope this is answer of your question
put the cors module as the first module that you load (use)
I finally solved this problem with code below.
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
next();
});

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

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.

express static 2 different folders

Files:
I have two different frontend build apps, each one in own directory - frontApp and frontAdmin and I need to send them on different requests
in routes/index.js
router.get('/', (req, res) => {
res.sendFile('index.html');
});
router.get('/admin', (req, res) => {
res.sendFile('admin/index.html');
});
I tried
in app.js
const frontPath = express.static(path.join(__dirname, '/frontApp'));
const adminPath = express.static(path.join(__dirname, '/frontAdmin'));
app.use(frontPath);
app.use('/admin', adminPath);
At the end i get the app on http://localhost:3000/admin/ but with errors
Sorry for incorrect question, the problem was in mime type
i did this and it works now
const frontPath = express.static(path.join(__dirname, '/frontApp'));
const adminPath = express.static(path.join(__dirname, '/frontAdmin'));
app.use(frontPath);
app.use(adminPath);
app.use('/admin', adminPath);

app.use express serve multiple html

I am using node.js and express for my site. I need to be able to direct the user when he clicks a link in index.html.
I have three pages: index.html, presentation.html, join.html all in the public folder.
This is how I did the routing in server.js:
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/_tmp'}));
And this is how I wrote the links in index.html:
<a class="btn" href="/presentation">Presentation</a>
<a class="btn" href="/join">Join</a>
when I run the server I get index.html but when I click one of the links to navigate to the other pages I get this error:
Cannot GET /presentation
When I try to add to server.js this:
app.get('/presentation',function(req,res){
res.render('public/presentation.html' , { root : __dirname});
});
I get this error:
TypeError: undefined is not a function
Here is my App layout:
App
/pulic
indx.html
join.html
presentatio.html
server.js
How can enable navigation?
I used mine and it worked
const express = require("express");
const app = express();
const router = express.Router();
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
var publicPath = path.join(__dirname, 'public');
router.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/"));
});
app.get('/new_deposit', function (req, res) {
res.sendfile(publicPath + '/new_deposit.html');
});
As it is configured, you can access the HTML files directly as files href="/join.html".
If you want to use routes for the static files, try this:
var publicPath = path.join(__dirname, 'public');
app.get('/test', function (req, res) {
res.sendfile(publicPath + '/test.html');
});
I found the error in the routes:
I was using either res.render or res.sendFile
when I used res.sendfile it worked fine.

Resources