I am getting the below screen-shot error when I try to serve my client-side code. When I am trying to run node server/server.js:
The below is my server.js code...
app.use(express.static(path.join(__dirname, "public")));
app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
app.all('/*', function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Access-Token,X-Key");
if(req.method === 'OPTIONS'){
res.status(200).end();
} else {
next();
}
});
app.all("/api/v1/*", [require('./middlewares/validateRequest')]);
app.use("/", require("./routes"));
app.use(function(req, res, next){
var err = new Error("Not found");
err.status = 404;
next(err);
});
Inside my routes/index.js, I have the following for get request.
router.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
Usually when the browser requests a JavaScript file, the server sends an HTML file. This is due to rules like app.get('*'.... So we need to tell the server to send the static files first and then declare the rules, like shown below:
// Declare static folder to be served. It contains the JavaScript code, images, CSS, etc.
app.use(express.static('build'));
// Serve the index.html for all the other requests so that the
// router in the JavaScript application can render the necessary components
app.get('*', function(req, res){
res.sendFile(path.join(__dirname + '/build/index.html'));
//__dirname : It will resolve to your project folder.
});
My folder structure
node(folder)
server.js
-client(f)
-index.html
-views(f)
-js(f)
-ctrl(f)
-service(f)
-app.js
-state.js
and
app.use(express.static('client'));
app.get('/index.html', function (req, res) {
res.sendfile(_dirname + '/index.html');
});
Call this from the browser: http://127.0.0.1:1956/index.html
var server = app.listen(1956, function (req, res) {
var host = server.address().address
var port = server.address().port
console.log("app listening at", host, port)
});
It's working fine for me.
I think this may be caused by your /public/index.html file.
When you include the JavaScript files in the index.html file, there's some problem with the "src" property. Thus it will return a "not found" HTML file instead of the actual JavaScript file.
I found the solution. The Node.js application tries to compile the JavaScript files inside the public folder, that makes a mistake; you defined the public folder like this:
app.use(express.static(path.join(__dirname, 'public')));
Try to define it using a virtual directory by adding a specific virtual folder name like this:
app.use('/static', express.static(path.join(__dirname, 'public')));
This should be work;
I guess part of the problem is in your router
In your routes/index.js change the get request to
router.get('/', function(req, res) {
res.sendfile('./public/index.html');
});
Also are you pipe-lining your assets using gulp or something similar? If not then how are you serving your assets?
I recommend you either serve your assets statically or use gulp
Related
I am trying to create an SPA using Express with following code
var express = require('express');
const path = require('path');
var app = express();
app.use('/assets', express.static(path.resolve(__dirname, 'www', 'assets')));
app.get('/*', (req, res)=>{
res.sendFile(path.resolve('www', 'index.html'));
});
var server = app.listen(3000, function(){});
This code works good but the problem is this responds with my index.html even when a file is not found in my assets folder. I want it to respond with error of 404 Not Found if some url is not present in assets folder
I tried using this code after line app.use('/assets'...
app.use(function (req, res, next) {
res.status(404).send("404 Not Found");
});
but not working
Issue is with
app.get('/*', (req, res)=>{
res.sendFile(path.resolve('www', 'index.html'));
});
Instead, use
app.get('/', (req, res)=>{
res.sendFile(path.resolve('www', 'index.html'));
});
So, I finally got the way to solve it
app.get('/*', (req, res)=>{
if(req.path.includes('/assets'))
{
fs.access(req.path, (err) => {
if(err)
{
res.status(404).send("Sorry can't find that!");
return;
}
});
}
res.sendFile(path.resolve('www', 'index.html'));
});
In the code, I have told to check if the request is about a file located in assets folder then check if the file exists, if does not exists then send 404 error with message and just return, otherwise do nothing but return the file.
I'm trying to get express static working with dynamic subdomain.
Basically http://ratty-doll-4811.localhost:3333 this subdomain is dynamic, and I load static folder based on this subdomain.
My issue is index.html loads but app.js which is in the same directory as index.html, doesn't load.
const subdomain = require('subdomain');
var app = Express()
app.use(subdomain({ base : 'localhost', removeWWW : true }));
app.get('/subdomain/:url', function(req, res, next) {
app.use('', Express.static(path.join(__dirname, 'public')));
res.sendFile('index.html', { root: __dirname + '/public' })
});
Here is the error:
You can't dynamically call app.use() because that will just build up route handlers over and over and they will accumulate indefinitely and be in force for all future requests. You can however, get the request handler from express.static() and call the request handler yourself dynamically.
I don't follow exactly what you're trying to accomplish, but this will show you how you can call it dynamically and then act differently based on whether it found a match of not.
// get express.static() handler
let staticHandler = Express.static(path.join(__dirname, 'public'));
app.get('/subdomain/:url', function(req, res, next) {
staticHandler(req, res, (err) => {
if (err) return next(err);
// it only gets here if the staticHandler didn't find a match and send a response
res.sendFile('index.html', { root: __dirname + '/public' })
});
});
I'm doing a simple node project to practice but i can't manage to serve html file with its css styles.
I believe that it worked fine for me before with the same code but now I don't understand why it doesn't run.
I searched about it and copied some code replacing the directory's name but it doesn't change anything.
Here is my code.
I also tried with path module to join the file name and the directory name.
app.use(express.static('public'));
app.get('/', (req, res)=>{
res.send("Welcome to our website");
});
app.get("/signup", (req, res)=>{
res.sendFile(__dirname + "/index.html");
});
//My directory:
testapp1
--node_modules
--public
--styles.css
--index.html
--app.js
--package.json
--package-lock.json
In the network tab of the developer console, it says that:
status: canceled
type: stylesheet
initiator: index.html
Size: 0B
time: 29ms
waterfall: "nothing"
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res, next) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
Try that instead.
I am use Nodes.js Express to do my route.
For the normal one... localhost:8080/Order its go work wells. But i am try to use use get method with the ID method localhost:8080/Order/ID-12345 and continue to ViewOrder.html to perform the function. But its shown out some error.
Error
Failed to load resource: the server responded with a status of 404 (Not Found)
localhost:1337/Orders/img/p7.jpg
Failed to load resource: the server responded with a status of 404 (Not Found)
localhost:1337/Orders/css/bootstrap.min.css
and etc..
Instead of
localhost:1337/css/bootstrap.min.css
// Index Page
app.get('/Order', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/Orders/:item', function (req, res) {
res.sendFile(__dirname + '/ViewOrder.html');
});
Order and Orders is not a directory. I used part of the route
code
Error
In your file server.js (the file that start your application) have you set the static dirname?
For me this resolve your problem:
var app = express();
app.use('/Orders', express.static(__dirname));
This setting set up the statics file for your project.
For more information this is helpfull express static resources
Yep! You need to specify your static folders in order serve static files.
So in your case i would do this to your server.js ;)
var express = require('express'),
app = express(),
http = require('http').Server(app);
const ipaddress = "127.0.0.1";
const port = 1337;
app.use(express.static(__dirname + '/Order'));
app.use(express.static(__dirname + '/Orders'));
app.get('/', function (req, res) {
res.sendFile('index.html', {"root": __dirname});
});
app.get('/:id', function (req, res) {
var param=req.params.id;/// hu! gotcha little param
res.sendFile('Orders/index.html', {"root": __dirname});
});
http.listen(port, ipaddress, function () {
console.log((new Date()) + ' Server is listening on port' + port);
});
UPDATE - according to comment (Actually Order is not a directory, I use Order as route to linked to directory – Brian)
Pretend a public folder would be your root/static this would be my second attempt
app.use(express.static(__dirname + '/public'));
app.get('/Order', function (req, res) {
res.sendFile('public/index.html', {"root": __dirname});
});
app.get('/Orders/:item', function (req, res) {
res.sendFile('public/ViewOrder.html', {"root": __dirname});
});
attention
i had to modify static requests
<link rel="stylesheet" type="text/css" href="style.css">
- TO -
<link rel="stylesheet" type="text/css" href="/style.css">
If you want your html pages to load css/js assets your need to serve them as static file ( documentation : http://expressjs.com/en/starter/static-files.html )
The image and bootstrap file can't be loaded because you haven't specified a static folder.
app.use('/media', express.static(__dirname + '/media'));
Using this, all files in the media folder can be requested by refering to them with /media/img/p7.jpg.
You may as well change the request path:
app.use('/static', express.static(__dirname + '/your/real/path'));
Thus you can refer to them like /static/img/p7.jpg.
How is the index.html (frontend Angular) getting called exactly?
In the tutorial, it was said that by having one of the following routes in route.js, frontend is getting called
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
----------or-------------------
app.get('*', function(req, res) {
res.sendfile('__dirname + '/public/index.html');
});
But even after removing that route, index.html is getting opened (or) If I rename index.html as index1.html at route and html file it is showing error.
Have you created a file index1.html in public folder? If yes, Use
res.sendfile('public/index1.html');
OR
var path = require('path');
res.sendFile(path.join(__dirname, '../public', 'index1.html'));
to render index1.html.
Note : sendfile is deprecated.