I have a set of routes on express which are brands.
Id like to serve 2 asset directories to each of these brands.
One public/static for all brand routes and then everything thats under public/brands/brandName.
Is this possible ? I have something like this which seems to work but only for the first /brandName i request.
var express = require('express');
var app = express();
var path = require('path');
app.get('/brands/:brand', function (req, res) {
app.use(express.static(path.join(__dirname, 'public/brands/' + req.params.brand)));
res.sendFile(__dirname + '/public/static/index.html');
});
app.listen(process.env.PORT || 3000, function () {
console.log('listening on port 3000!');
});
app.use(express.static(path.join(__dirname, 'public/static')));
module.exports = app;
This should do the trick;
app.use('/brands', express.static(path.join(__dirname, 'public/brands/')));
app.use('/static', express.static(path.join(__dirname, 'public/static/')));
app.get('/brands/:brand', function (req, res) {
res.sendFile(__dirname + '/public/static/index.html');
});
Related
I am having a problem with Node.JS.
I'm trying to upload a HTML file with Node.JS (the HTML file has links to JS, JSON and CSS files) but when I turn on the server and look at the page, only what was in the HTML is written, which means there is no CSS and no JS which were working properly before I implemented the server.
Can anyone help me?
Here's the Node.JS code:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static('project-folder'));
app.get('/', function(req, res){
res.sendFile('website.html', { root: __dirname });
});
app.listen(port, function(){
console.log("server is up");
});
If your folder structure looks like this:
project-folder
|-website
| |-style.css
| |-script.js
|-website.html
|-server.js
then the code should look like this:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.use(express.static(path.join(__dirname, 'website')));
app.get('/', function(req, res){
res.sendFile('website.html', { root: __dirname });
});
app.listen(port, function(){
console.log("server is up");
});
if it's like this:
project-folder
|-website
| |-style.css
| |-script.js
| |-website.html
|-server.js
then the code should look like this:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.use(express.static(path.join(__dirname, 'website')));
app.get('/', function(req, res){
res.sendFile('website.html', { root: path.join(__dirname, 'website') });
});
app.listen(port, function(){
console.log("server is up");
});
Mind the path module that is required at the top
Very new to express and file system and don't have much idea about directories so getting this error.
var express= require('express');
var path= require('path');
var mysql= require('mysql');
var bodyParser= require('body-parser');
var app= express();
app.get('/', function(req, res) {
res.set( {
'Access-control-Allow-Origin': '*'
});
return res.redirect('/public/signup.html');
}).listen(2121);
console.log('server Running on : 2121');
app.use('/public',express.static(__dirname +"/public"));
Getting error "Cannot GET /public/signup.html"
My directories is:
-Express
--Server.js
--public
---signup.html
Looks like your code is a little jumbled up. Separate out your port listener - this should always come last. Add your routes and middleware before that as individual calls to app, and also register your get request to redirect back to your server to the signup html.
This should work:
var express = require("express");
var path = require("path");
var port = 2121;
var app = express();
// Register Middlewares/Headers
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
// Register Static
app.use("/public", express.static(__dirname + "/public"));
// Register redirect
app.get('/', (req, res) => {
res.redirect(req.baseUrl + '/public/signup.html');
});
app.listen(port, () => {
console.log("server Running on : ", port);
});
You're calling listen on app before you call use on your middleware and there are a few mistakes in your code. I think this should work:
app
.use('/public',express.static(`${__dirname}/public`))
.get('/', (req, res) => {
res.header({
'Access-control-Allow-Origin': '*'
});
res.redirect(`${req.baseUrl}/public/signup.html`);
})
.listen(2121);
You should provide
app.use('/public',express.static(__dirname +"/public"));
Before you using app.get
Full example:
var express= require('express');
var path= require('path');
var mysql= require('mysql');
var bodyParser= require('body-parser');
var app= express();
app.use('/public',express.static(__dirname +"/public"));
app.get('/', function(req, res) {
res.set( {
'Access-control-Allow-Origin': '*'
});
return res.redirect('/public/signup.html');
}).listen(2121);
console.log('server Running on : 2121');
I have this code:
var express = require("express");
var app = express();
var path = require("path");
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/views/index.html'));
res.set('Access-Control-Allow-Origin', '*');
}).listen(3000);
console.log("Running at Port 3000");
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
I will have many services (like the test one), and I don't want to have them all on the same file.
I read in another question in Stack Overflow, that I can require other files like this: var express = require("./model/services.js"); And in that file write all the services, but it's throwing app is not defined when I start Node.
How can I separate codes?
You can define your routes in different files say test-routes.js like this:
module.exports = function (app) {
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
}
Now in your main file say server.js you can import your route file like this:
var express = require("express");
var app = express();
var path = require("path");
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/views/index.html'));
res.set('Access-Control-Allow-Origin', '*');
}).listen(3000);
console.log("Running at Port 3000");
// import your routes
require('./test-routes.js')(app);
your test.js should look something like:
var express = require('express');
var router = express.Router();
router.get('/test', function (req, res) {
res.json(200, {'test': 'it works!'});
});
module.exports = router;
and the app.js (assuming other is some other route defined similarly to test.js):
var test = require("./routes/test.js");
var other = require("./routes/other.js");
...
//all your code for creating app
...
app.use('/test', test);
app.use('/other', other);
I am working on a single page web app using Node + Express and Handlebars for templating. Everything currently works well from index.html, which is served from a pretty standard server.js file:
var express = require('express');
var server = express();
server.use(express.static(__dirname + '/public'));
var port = 10001;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
This works perfectly when loading from http://localhost:10001/. My issue is that I'm using push states in the app, so the browser may show a URL like http://localhost:10001/foo/bar and then if I refresh the page, I get the error Cannot GET /foo/bar since there is no route for this.
So my question, and pardon my incredible noobishness when it comes to Node, can I make it so all requests route to index.html? The JavaScript in my app can handle showing the right content based on URL params on page load. I don't want to define custom routes as the number would be large, and the paths for them can change dynamically.
const express = require('express')
const server = express()
/* route requests for static files to appropriate directory */
server.use('/public', express.static(__dirname + '/static-files-dir'))
/* other routes defined before catch-all */
server.get('/some-route', (req, res) => {
res.send('ok')
})
/* final catch-all route to index.html defined last */
server.get('/*', (req, res) => {
res.sendFile(__dirname + '/index.html');
})
const port = 8000;
server.listen(port, function() {
console.log('server listening on port ' + port)
})
This pattern will serve static assets before hitting the catch-all route that serves up your front-end application. To register any additional routes, just add them above the catch-all route.
var express = require('express');
var server = express();
// middleware
server.use(express.static(__dirname + '/public'));
// routes
server.use('*', function (req, res) {
// serve file
});
var port = 10001;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
This short thing works well:
import express from "express";
const app = express(),
staticServe = express.static(`${ __dirname }/public`);
app.use("/", staticServe);
app.use("*", staticServe);
Just make sure that all URLs from your HTML/JS files are absolute now, as all resources that do not exist will return index.html file.
Express v 4.15.2
var app = express();
var options = {
dotfiles: 'ignore',
etag: true,
extensions: ['htm', 'html'],
index: 'index.html',
lastModified: true,
maxAge: '1d',
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
res.header('Cache-Control', 'public, max-age=1d');
}
};
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use('/', express.static(__dirname + '/public', options));
app.use('*', express.static(__dirname + '/public', options));
var express = require('express');
var server = express();
server.use(express.static(__dirname + '/public'));
server.get('*', function(req, res){
res.sendFile('index.html');
});
var port = 10001;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
I have following code:
var express = require('express'),
app = express();
app.use(express.static(__dirname + '/static'));
app.get('/', function(req, res) {
//???
});
app.listen(80);
How first perform the function and then send a static file?
Now sent only a static file.
var express = require('express'),
app = express();
app.use(app.router); //<------------this way
app.use(express.static(__dirname + '/static'));
app.get('/', function(req, res, next) {
//actions
//send index
next();
});
app.listen(80);