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.
Related
Just a quick question. Say I have 2 different static HTML files that I want to serve in Express, index.html and contact.html. I've been fiddling around and I currently use this barebone Express code to serve them:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static('public'))
app.get('/', function (req, res) {
res.sendFile('/index.html');
});
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/public/contact.html');
});
app.listen(3000, function () {
console.log('runnning on port 3000')
});
Question is, I tried to serve contact.html using
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
but it always resort to the root directory instead of the public directory. OTOH, I can server index.html just fine without having to explicitly adding /public in the response.
Can anybody point me what's the cause for that?
Thanks.
For the given file structure:
yourapp
|-- contact.html
|-- index.html
`-- server.js
The following code would work just fine:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/contact', function (req, res) {
res.sendFile(__dirname + '/contact.html');
});
Assuming both index.html and contact.html have read access.
Remember, sendFile requires an absolute path and __dirname refers to your app directory. Make sure you give references according to your file location.
I am currently working on a project which is a webpage using angular to dynamically change DOM elements. Within the project is a public folder which contains all HTML, CSS, JavaScript and JSON objects. The project must be distributed so I am using node to run from localhost. This is my server.js code:
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req,res){
res.sendFile(path.join(__dirname + '/public'));
});
app.listen(8080, function(){
console.log((new Date()) + " Server is listening on port 8080");
});
When I head to localhost:8080 it just says Cannot GET /. Where am I going wrong?
The correct way to serve static files with express is as follows:
//Look for statics first
app.use(express.static(path.join(__dirname, 'public')));
//Return the index for any other GET request
app.get('/*', function (req, res) {
res.sendFile('index.html', {root: path.join(__dirname, 'public')});
});
Edit: on a side note this may be worthwhile to mention that app.get should be the last route declared in node so if you want API endpoints exposed declare them above (before) the final app.get.
You forgot to point to the actual html file you want to display. If you have a index.html in your public directory, just point tot '/public/index.html' . That works (tested it here).
Followed user Muli's answer and all files are now being served correctly. Code here:
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req,res){
res.sendFile('index.html', {root: path.join(__dirname, './public')})
});
app.listen(8080, function(){
console.log((new Date()) + " Server is listening on port 8080");
});
I have a public folder in which I put an angular2 app. Now I am trying to setup an express server with a catchall route that always returns index.html. To be clear - according to this question I need to map all of my routes to index.html.
If I access the base server URL (localhost:10001), everything works as expected. But when I go to a route(let's say localhost:10001/landing), and refresh the page, I get the following error:
Error: ENOENT: no such file or directory, stat
'/Users/shooshte/express-test/index.html' at Error (native)
This is my server configuration:
var express = require('express');
var static = require('serve-static');
var server = express();
// middleware
server.use(express.static(__dirname + '/public'));
// routes
server.use('*', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
var port = 10001;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
What am I doing wrong?
You're missing the public directory in the path to index.html:
res.sendFile(__dirname + '/public/index.html');
i think you don't have your index.html in either public or your root folder /Users/shooshte/express-test/
this is the only resion you are getting this error
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
I finally got everything working on a certain page, but the issue I'm facing now is when I create additional pages. I realize the issue must be with my routing, but I'm not sure how to change the server side code without effecting my app.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
// socket functions
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
I would like to serve html in a folder 'public' and have files like index.html and other.html in there.
Configure your express app to use a static directory.
app.use(express.static('public'));
All files located under public can now be accessed. So a file called index.html can now be reached via /index.html
Further documentation can be found here:
http://expressjs.com/starter/static-files.html
If your folder is called public then you could do something like
app.use(express.static('./public'))
.get('/', function(req, res) {
res.sendFile('index.html', {root: 'public/'});
})