Express - static file being served cannot be located - javascript

I am trying to serve static files (CSS stylesheets) with Express, and it is located when I am on some routes such as the home page / or index page /index. However, when I navigate to a /index/:id page, I get this error in the chrome console:
GET http://localhost:3000/index/stylesheets/styles.css net::ERR_ABORTED
I'm sure that the reason why I am getting this error is because the css file is not actually served in the location stated in the error. I verified that the actual location that it is being served is http://localhost:3000/stylesheets/styles.css.
I have this following line of code in my server file: to serve the css file app.use(express.static(__dirname + "/public"));
and this is the code for the /index/:id route:
app.get('/index/:id', function(req, res) {
Post.findById({_id: req.params.id}, function(err, foundPost){
if (err) {
console.log(err);
res.redirect('/');
}
else {
res.render('./index/show', {post: foundPost});
}
});
});
and I made sure to add the CSS to every html page being served with this exact line:
<link rel="stylesheet" href="stylesheets/styles.css" />
Why is the CSS included for routes such as / or /index, but looks in the wrong place for it when I navigate to a /index/:id page? The location that the page is looking for the css file in changes from http://localhost:3000/stylesheets/styles.css to http://localhost:3000/index/stylesheets/styles.css depending on the route I am on.
What am I missing? Any help is much appreciated!

This works for me-
app.use(express.static('public'));

Related

Problems while loading CSS tied to an EJS page while using res.redirect()

So I'm using express with ejs where I've this as my base route
router.get("/", productsData.getProducts);
where productsData is from my controllers page and this is the code there
exports.getProducts = (req, res, next) => {
res.render("shop/index", { pageTitle: "Shop", path: "/" });
};
network tab in the developer tools show the css files werent loaded
On checking it I saw net::ERR_EMPTY_RESPONSE on the request for the css files.
If I reload the page it works fine and the css are loaded. This is the code for the CSS import.
<link rel="stylesheet" href="/css/main.css" />
The only thing that goes wrong is when It redirects here
exports.postAddProduct = (req, res, next) => {
const product = new Product(req.body.title);
product.save();
res.redirect("/");
};
Can anyone tell whats going wrong, is it with something with res.redirect() or something else?
Actually the code was good, I was saving the form uploads in a file in the directory same as my code while using nodemon, which was watching the whole code. So everytime I submitted the form, it restarted the server because of which this issue occurred.

Javascript/node link main.js

So I am just learning and I am trying to build a web app using node, I know I could use express but I am trying to build it all using Node to get a better understanding.
The problem is I cant get the main.js page to load on the app.
I have a router module that builds the page eg
function home(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(fs.readFileSync('./views/header.html'));
res.write('<style>' + fs.readFileSync('./css/styles.css') + '</style>');
res.write(fs.readFileSync('./views/startpage.html'));
res.end(fs.readFileSync('./views/footer.html'));
};
and the script tag is in the footer partial just before the closing body tag, would i need to load it a different way ?
Here is the full app if this is not enough information, thanks
https://github.com/naassi/taxi-log
You probably want a static file server for all your css and javascript files. Instead of sending the CSS file content in home, include
<style>./css/styles.css</style>, and answer the request for *.css files with the appropriate file:
function staticServer(req, res) {
fs.readFile(__dirname + req.url, function (err,data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
});
})
In footer, you want to load a .js file - your Node server is responsible for serving that, just like it handles a request for e.g., home.
If you're learning Node, try to stay away fron Sync functions, they block the event loop, and defeat Node's good parts :)

Express js getting 404 for all static files in a directory

I have multiple directories for my convenience for my static files.
Some of my static files are in client directory and some dashboard related files are in src directory so now my directory structure is as follows
/
|
client //static files and other stuff
server //server side express, app, controller, models etc
src //other static files
I have two angular apps one in client folder and another in src folder and my server side routes are as follows -
app.route('/app/dashboard-v1').get(function(req,res){
res.sendFile(path.join(__dirname, '../src', 'index.html'));
});
// All undefined asset or api routes should return a 404
app.route('/:url(api|img|src|auth|components|app|bower_components|assets)/*')
.get(errors[404]);
// All other routes should redirect to the index.html
app.route('/*')
.get(function (req, res) {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
So my first angular app is in app/dashboard-v1 and all other urls are redirected to app2
I am getting all the files in my app2 correctly but I am getting 404 for all other files in my second app.
now If I comment out the
// app.route('/:url(api|img|src|auth|components|app|bower_components|assets)/*')
.get(errors[404]);
I am getting my index.html from second app in all files in first app instead of the 404 error
My express configuration is as follows -
if ('production' === env) {
app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
app.use(express.static(path.join(config.root, 'public')));
app.set('appPath', path.join(config.root, 'public'));
app.use(morgan('dev'));
} else {
app.use(require('connect-livereload')());
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(path.join(config.root, 'client')));
app.use(express.static(path.join(config.root, 'src')));
app.set('appPath', path.join(config.root, 'client'));
app.use(morgan('dev'));
app.use(errorHandler()); // Error handler - has to be last
}
I am assuming something is wrong with my routes. How do I fix this ?
In my index.html in first app(app/dashboard-v1) I have added the
<base href="/src/" />
and all the links inside my index.html are relative like the following is a block from src/index.html (app/dashboard-v1 url app)-
<script src="vendor/angular/angular-animate/angular-animate.js"></script>
<script src="vendor/angular/angular-cookies/angular-cookies.js"></script>
and when I open the network console in my browser the request that is made to the server is like this -
Request URL:http://localhost:9000/src/vendor/angular/angular-animate/angular-animate.js
to which I am getting a 404 status code in browser console
Do you run the app on the / direcotry of your example?
I think that you ahve to set __dirname as the static folder
app.use('/',express.static(__dirname));
or if you want you can set specific folders likt this:
app.use("/public", express.static(__dirname + "/public"));
app.use("/public2", express.static(__dirname + "/public2"));

Node js 404 and angular url refresh conflict

I am making an Nodejs and angular js app. I had to make a page loads when someone type on url and enter it. It worked fine until I also made a script to redirect to 404 error page. Now the problem is with both script only one of the criteria works. When 404 redirection works i cannot go to the page with url typed on browser and when that works then 404 page is redirected to index. html.
Here are the two scripts that I have use.
app.use(function(req, res) {
res.render('404', {layout: false, title: '404: File Not Found'});
});
app.use('/*', function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
Am I doing anything wrong over here. Beside this I also have my general routes which works fine in angular app when I click it from navigation.
Put 404 handler code at end (It must be last route)
Use your code like this:
app.use('/*', function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.use(function(req, res) { //put this at end
res.status(404);//add this line for setting 404 status
res.render('404', {layout: false, title: '404: File Not Found'});
});
The 404 route must be the last route.
Put this before your 404 route:
app.use('/reload/reload.js', express.static('node_modules/reload/lib/reload.js'));

Node.js redirecting style and resource folder based on subdomain

I have this server.js file that creates a localserver.
//server.js
var connect = require('connect');
connect.createServer(
connect.static(__dirname)
).listen(8080);
It uses the node package connect to start a localhost on the same dirname where my webapp is. I would like to extend this code so I can have a subdomain.
When I place the address localhost:8080/companyA I want the link:
<link rel="stylesheet" href="resources/css/bootstrap.css" type="text/css" />
to be redirected to:
<link rel="stylesheet" href="companyA/css/bootstrap.css" type="text/css" />
so resuming. I want my website to be styled according to the subdomain. Only the resource folder will be redirected.
Hope someone can help. Thanks
NOTE: I would like to keep the index file plain without using a template for it or a markup language. Basically I should be able to achieve that using some routing rules.
You can address the redirect using Jade markup language. For example
app.get('/:company/path', function(req, res){
var subdomain = req.params.company;
res.render('myview', {subd: subdomain});
});
now inside the view, myview.jade
link(rel='stylesheet', href=#{subd}/css/bootstrqp.css, type="text/css")
another option is to accomplish the redirect solely in the route
app.get('/:company/css/:file', function(req, res){
var options = {
root: __dirname + '/public/' + req.params.company, // wherever your css files are located
dotfiles: 'deny',
index: false
headers: {
'x-timestamp': Date.now(),
'x-sent': true
};
};
res.sendFile(req.params.file, options, function(err){
// css files sent. hooray!
});
});

Categories

Resources