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);
Related
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')));
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'))
})
After trying to log some data on index file. I found my express server execute twice. Why do i get this error/bug?
Running Node 12.13.0 LTS, Express 4.17.1 and latest packages versions by the date of this post. I’ve tried on commenting some parts of code and always seem to end up running twice.
My app.js code:
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const path = require('path');
const bodyParser = require('body-parser');
const favicon = require('serve-favicon');
const app = express();
// ENV Variables
require('dotenv').config();
const PORT = process.env.PORT;
// Authentication Packages
const session = require('express-session');
const passport = require('passport');
// Middlewares
app.use(favicon(path.join(__dirname,'public','images','favicon.ico')));
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.json());
app.use(session({
secret: 'GBR6N7^?5Xx-Ldqxf&*-Hv$',
resave: false,
saveUninitialized: false,
//cookie: { secure: true }
}));
app.use(passport.initialize());
app.use(passport.session());
// View Engine
app.use(expressLayouts);
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// Routes
app.use('/', require('./routes/index'));
// Controllers
app.use('/profile', require('./routes/profile'));
app.use('/products', require('./routes/products'));
app.use('/bookmarks', require('./routes/bookmarks'));
// Catch 404
app.use((req, res) => {
res.render('pages/404');
});
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
and my index.js code:
const express = require('express');
const router = express.Router();
// Official pages
router.get('/', (req, res) => {
// THIS IS THE CODE I GET TWICE ON CONSOLE
console.log(req.user);
console.log(req.isAuthenticated());
// THIS IS THE CODE I GET TWICE ON CONSOLE
res.render('pages/index');
});
router.get('/about', (req, res) => {
res.render('pages/about');
});
router.get('/features', (req, res) => {
res.render('pages/features');
});
// Footer pages
router.get('/terms', (req, res) => {
res.render('pages/terms');
});
router.get('/refunds', (req, res) => {
res.render('pages/refunds');
});
module.exports = router;
Also i have those two functions on my profile.js (for passport.js):
passport.serializeUser((userId, done) => {
done(null, userId);
});
passport.deserializeUser((userId, done) => {
done(null, userId);
});
I get those results twice:
console.log(req.user);
console.log(req.isAuthenticated());
Output (Executed twice!):
undefined
false
undefined
false
and I expect one:
undefined
false
Due to how Express routing works, the path / will match / and /about and /favicon.ico etc. This is because Express supports not just endpoint routing but also path mounting. In other words, express supports things like this:
const app = express();
const route = express.Router();
route.get('/world', (req, res) => { res.send('hello') });
app.get('/hello', route); // mounts world to hello
// so we can access /hello/world
In order to support the feature above, express needs to interpret paths such as /hello to mean both /hello and /hello/anything/else. It needs to treat it as both the endpoint and potentially just a path leading to an endpoint.
This means that if you have a path:
app.get('/', () => {});
It will also trigger if the browser requests /favicon.ico. And browsers request favicon.ico to draw the tiny icon in the browser tab. This is why your route is triggered twice.
A few things to keep in mind when writing Express routes/controllers:
Make sure that the / path is last because otherwise it will also respond to requests to all your other paths.
If you are using express.static() make sure it is set up before the / path. Yes, the first rule above should also cover this but I see this issue often enough that it merits its own point.
In your case you can possibly fix the issue by simply creating a favicon.ico icon and saving it in the static (public) folder.
I am using Express with Node and then building a React app with this which is single page, except one static HTML file.
I have this working locally, so when I go to localhost:3000/static-file.html, I can see the file. But this doesn't work in production.
I can't even hit any of the test console.log statements, so I know that nothing is being hit when requesting static-file.html. Please see below part of my app.js file:
if (process.env.NODE_ENV === "production") {
app.get('/static-file.html', function (req, res) {
console.log('test1');
});
app.get('static-file.html', function (req, res) {
console.log('test2');
});
app.get('static-file', function (req, res) {
console.log('test3');
});
app.get('/static-file', function (req, res) {
console.log('test4');
});
app.use(express.static("client/build"));
}
When I go to production-site.com/static-file.html - I just see the index still, unlike with localhost.
Can anybody help me on that? Thanks so much.
Try something like this:
const express = require('express');
const app = express();
const path = require('path');
// the __dirname is the current directory from where the script is running
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/build/index.html'))
})
/* Here build is the production build directory and index.html is the main html page to show */
I am trying to make az ExtJS application with a Node.js server. My server code currently looks like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
When I open localhost:3000 in a browser, the html file is load, but not correctly. Checking in firebug I see that itt cannot find the linked files in html. For example
"NetworkError: 404 Not Found - http://localhost:3000/ext-4/ext-debug.js".
This is quite logical, since the file doesn't exist on that URL. My question would be how to fix this issue, so it could find every single linked file on my filesystem.
I'm clearly doing something wrong or missing something, I am totally new in node.
Doesn't look like you're configuring Express' static file handler.
Try adding this code:
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
It would go right after var app = ... like this:
var express = require('express');
var app = express();
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
And then place your static files under the ./public directory.
You'll want to use some static middleware such as: http://www.senchalabs.org/connect/static.html
note express inherits connect so you can
app.use(express.static(filedir));
Or the full thing:
var express = require('express');
var app = express();
app.use(express.static(filedir));
app.get('/employees', function(req, res){
console.log("hello");
res.send("hello");
});
app.listen(3000);