Here is a picture of my project directory.
I have my logo in the template/assets/logo.png.
In my server.ts file, I use middleware express as app.use( express.static( "template" ) );
unfortunately, When I try to display the logo in my html file, it doesn't display.
<img src="assets/logo.png" alt="Logo">
Here is my server.ts file:
// Import everything from express and assign it to the express variable
import express from 'express';
import fs from 'fs';
// Import WelcomeController from controllers entry point
import {WelcomeController} from './app/controllers';
// Create a new express application instance
const app: express.Application = express();
// The port the express app will listen on
const port: any = process.env.PORT || 3000;
// Template folder
app.use( express.static( "template" ) );
// Mount the WelcomeController at the /welcome route
app.use('/', WelcomeController);
// Serve the application at the given port
app.listen(port, () => {
const source = fs.createReadStream('/src/app');
const dest = fs.createWriteStream('/dist');
source.pipe(dest);
source.on('end', function() { /* copied */ });
source.on('error', function(err) { /* error */ });
// Success callback
console.log(`Listening at http://localhost:${port}/`);
});
What would be the way to display my templates with the files showing?
I was doing this wrong app.use( express.static( "template" ) );
I should be doing app.use(express.static(__dirname + '/app/template'));
i think you need to define what the root directory is first in express before importing assets (at least, it helps!)
so if you import express and then assign express() to a variable ,e.g.
var express = require express();
var app = express;
then you could do something like:
var root = require('path').join(__dirname,'/template');
app.use(express.static(root));
Once the root is defined, all further files will be called from that place when a url is referenced.
hope this helps
Related
I am learning express js.
Here I am creating a crud project in student data. I have created routes and controllers but when I include it in my main app.js , my router seems not working.
Please guide me.
P.S:I am working on ES6.
My app.js
import express from 'express';
import connectDB from './db/connectdb.js'
import web from "./routes/web.js"
import{join} from 'path'
const app = express();
const port = process.env.PORT || "8080"
const DATABASE_URL ="mongodb://127.0.0.1:27017"
//loading static files
app.use('/student',express.static(join(process.cwd(),"public")))
//loading routes
app.get('/student',web)
//set template engine
app.set("view engine","ejs")
app.listen(port,()=>{
console.log("Server listening at port no:"+port)
})
connectDB(DATABASE_URL)
My router file saved as web.js
import express from 'express';
import StudentController from "../controllers/studentController.js"
const router = express.Router();
router.route('/',StudentController.getAllDoc)
export default router
My studentController.js
class StudentController{
static getAllDoc = (req,res)=>{
res.render('index')
}
}
export default StudentController
I expected my ejs file named as index.ejs to run which is in views folder, but the result is like cannot get /student/
.use is used to register middleware, serve group of route,...
.get, .post is a single route.
Please change your code to something like this:
app.js
//loading static files
app.use(express.static(join(process.cwd(),"public")))
//loading routes
app.use('/student',web)
web.js
const router = express.Router();
router.get('/',StudentController.getAllDoc)
export default router
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!`);
});
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
I am using angular 6 and implemented the angular universal for server side page rendering,
Everything works fine but I am getting continues error in my console.
ERROR [Error]
ERROR [Error]
And I have declared window as global variable still I am getting errors like this
Unhandled Promise rejection: window.some_function is not a
function
my server.ts file
//
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '#angular/core';
import * as express from 'express';
import { join } from 'path';
// Express Engine
import { ngExpressEngine } from '#nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '#nguniversal/module-map-ngfactory-loader';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// node run port
const port = 6065;
// Express server
const app = express();
const PORT = port || process.env.PORT;
const DIST_FOLDER = join(process.cwd(), 'dist');
const domino = require('domino');
const fs = require('fs');
const MockBrowser = require('mock-browser').mocks.MockBrowser;
const mock = new MockBrowser();
const template = fs
.readFileSync(join(DIST_FOLDER, 'browser', 'index.html'))
.toString();
// Make all Domino types available as types in the global env.
Object.assign(global, domino.impl);
(global as any)['KeyboardEvent'] = domino.impl.Event;
const win = domino.createWindow(template);
win.Object = Object;
win.Math = Math;
global['window'] = win;
global['document'] = win.document;
global['navigator'] = mock.getNavigator();
global['branch'] = null;
global['object'] = win.object;
global['HTMLElement'] = win.HTMLElement;
global['DOMTokenList'] = win.DOMTokenList;
global['Node'] = win.Node;
global['Text'] = win.Text;
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));
// TODO: implement data requests securely
app.get('/api/*', (req, res) => {
res.status(404).send('data requests are not supported');
});
// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render('index', { req });
});
// Start up the Node server
app.listen(PORT, '0.0.0.0', () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
I had the same problem and started debugging server.js in my Visual Studio Code and what I had found: an error messages was caused by http requests from TranslateHttpLoader (I'm using ngx-translate), which was trying to load .json-files with translations. After some googling I found this thread where you can find how to enable server-side translation loading. After that error messages disappeared.
Is there any way I can always serve the same file?
So, if they go to website.com/ajsdflkasjd it still serves the same file as website.com/asdnw
I would like to do this using express with node.
The file I have is a static html file, not a jade file.
By the way, the reason I'm wanting to do this, in case you were wondering, is I have an angularjs app that handles all the routing for me. So, all I need to do is serve that one page, and it will take care of the rest.
Thanks in advance!
new answer
const app= require('express')()
// static file serve
app.use(express.static(__dirname))
// not found in static files, so default to index.html
app.use((req, res) => res.sendFile(`${__dirname}/index.html`))
app.listen(3000)
old answer
var express = require('express');
var bodyParser = require('body-parser')
var path = require('path')
var app = express();
// url encoding
app.use(bodyParser.urlencoded({extended:false}));
// gzip
// redirect all html requests to `index.html`
app.use(function (req, res, next) {
if (path.extname(req.path).length > 0) {
// normal static file request
next();
}
else {
// should force return `index.html` for angular.js
req.url = '/index.html';
next();
}
});
// static file serve
app.use(express.static(__dirname))
app.listen(3000)
Below is what I'm using express with angularjs in my project. It will always send index.html unless the browser requests resource files (images, css, js, etc.) which contains extname.
var express = require('express');
var app = express();
app.configure(function () {
// url encoding
app.use(express.urlencoded());
// gzip
app.use(express.compress());
// redirect all html requests to `index.html`
app.use(function (req, res, next) {
if (path.extname(req.path).length > 0) {
// normal static file request
next();
}
else {
// should force return `index.html` for angular.js
req.url = '/index.html';
next();
}
});
// static file serve
app.use(express.static(__dirname));
});
Basic configuration for Express 4 is:
var express = require('express');
express()
.get(/.*/, function(req, res) {
res.sendFile('index.html', {
root: __dirname
});
})
.listen(8080);
Working example
Those snippets with GZip, BodyParser etc. are pretty cool, but I think over-complicated if you want to just test your single page app. Of course you can add all this "production stuff" when it starts to be needed.
Read more:
sending files
routing
Here a simple implementation with ExpressJs to create a virtual host and whenever return the index.html
var express = require('express');
var app = express();
var vhost = require('vhost');
// Function to create virtualhost
function createVhost(domain,rootDirectory){
var exp = express();
exp.use(express.static(rootDirectory));
exp.get(/.*/,function(req,res){
res.sendFile('index.html',{root:rootDirectory});
})
app.use(vhost(domain,exp));
}
// Virtual Host to create
createVhost('example.com','/home/[user]/[www]/[example.com]');
createVhost('othersite.com','/home/[user]/[www]/[othersite.com]');
// Start Server
app.listen(80,function(){
console.log('Node server on port 80');
});
Remember:
Add the domains in the "/etc/host" (in linux)
127.0.0.1 example.com
127.0.0.1 othersite.com
And run in the terminal the "app.js" with "sudo" for port 80
~/home/[server]$ sudo node app.js
You can do this in both angular as well as node side.
In Node side you can do something like this:
res.sendfile('<ur html file path');
In Angular if you using ui-router you can make use of
$urlRouterProvider.otherwise('/otherwise');
and this otherwise state needs to be defined as well
$stateProvider
.state("otherwise", { url : '/urPage'...})
If you using ngRoute, you can do
$routeProvider.otherwise({redirectTo: '/urPage'});
UPDATE
Since your routers are not configured to show a default urPage, in the server you can have something as:
var app = express.createServer();
app.get('/urPage',function(req,res){
res.sendfile('<ur html page>');
});