I am using node.js and express for my site. I need to be able to direct the user when he clicks a link in index.html.
I have three pages: index.html, presentation.html, join.html all in the public folder.
This is how I did the routing in server.js:
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '/_tmp'}));
And this is how I wrote the links in index.html:
<a class="btn" href="/presentation">Presentation</a>
<a class="btn" href="/join">Join</a>
when I run the server I get index.html but when I click one of the links to navigate to the other pages I get this error:
Cannot GET /presentation
When I try to add to server.js this:
app.get('/presentation',function(req,res){
res.render('public/presentation.html' , { root : __dirname});
});
I get this error:
TypeError: undefined is not a function
Here is my App layout:
App
/pulic
indx.html
join.html
presentatio.html
server.js
How can enable navigation?
I used mine and it worked
const express = require("express");
const app = express();
const router = express.Router();
const path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
var publicPath = path.join(__dirname, 'public');
router.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/"));
});
app.get('/new_deposit', function (req, res) {
res.sendfile(publicPath + '/new_deposit.html');
});
As it is configured, you can access the HTML files directly as files href="/join.html".
If you want to use routes for the static files, try this:
var publicPath = path.join(__dirname, 'public');
app.get('/test', function (req, res) {
res.sendfile(publicPath + '/test.html');
});
I found the error in the routes:
I was using either res.render or res.sendFile
when I used res.sendfile it worked fine.
Related
How do i stop access to index .html file and let people sign up on home.ejs, i was building a static website but now making a web app and want people to sign up.
i commented out the index section but still the index gets on first instead of home.
I want people to sign up first and then use the app
This is my code.
//jshint esversion: 6
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
/* app.get("/", function(req, res){
res.sendFile(path.join(__dirname, "public", "index.html"));
}); */
app.get("/home", function(req, res){
res.render("home")
})
app.listen(3000);
console.log('now the server is running')
App using static assets from public which includes your index.html file.
You can remove index.html from a static source
app.get("/", function(req, res){
res.sendFile(path.join(__dirname, "views", "index.html"));
});
Or you can give a base path to static folder.
app.use('/public' ,express.static(path.join(__dirname, 'public')));
When I host my front-end on Nodejs, I use app.use(express.static(path.join(__dirname, "public")));. However, this makes me put the name of the HTML file at the end of the URL; for example, localhost:3000/index.html.
How would I make it show the front-end at the base URL, in this case, "localhost:3000/". I have attached a part of my Nodejs code. I would appreciate any help and thank you in advance.
var path = require('path');
var express = require('express');
const app = express();
const port = process.env.PORT || '3000';
app.use(express.json());
app.use((req, res, next) => {
console.log(req.path);
next();
});
app.use(express.static(path.join(__dirname, "public")));
app.listen(port, () => console.log("Server is ready"));
You can use a route path and sendFile method:
app.get("/", function(req,res) {
res.sendFile("index.html", {root: path.join(__dirname, "public")})
})
More details here
This is how you would do.
//for static files like css and html
app.use('/static', express.static(path.resolve(__dirname, path to css and js)));
app.get('/*', (req, res)=>{
res.sendFile(path.join(__dirname, 'path to your html file'))
})
Under my server.js i have the following
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendFile('index.html');
});
app.get('/report', function(req, res){
res.sendFile('report.html');
});
When i start the server and render on http://localhost:8000 i am able to see index.html, but on http://localhost:8000/report i am unable to render report.html and instead i get an path error path must be absolute or specify root to res.sendFile
My directory structure is
public
index.html
report.html
Why i am getting this error?
By default, express.static() will serve up index.html when just / is requested (see reference in the doc). So, your index.html is being served by the express.static() middleware, not by your app.get('/', ...) route.
So, both your app.get() routes would likely have the exact same issue. The first one just isn't being called because your express.static() configuration is already handling that request and sending back index.html.
The /report route is not being handled by express.static() because report is not the same request as report.html. Thus, the middleware does not handle the request so then your misconfigured app.get('/report', ...) handler is invoked and you get the error about it being misconfigured.
This should be all you need:
var express = require("express");
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/report', function(req, res){
res.sendFile(__dirname + "/public/report.html");
});
app.listen(8080);
Or, you can use the path module and join the pieces with path.join():
var path = require("path");
And, then serve the file with this:
res.sendFile(path.join(__dirname, 'public', 'report.html'));
In my own sample nodejs app, either of these res.sendFile() options work.
npm install path
then, you have to specify the root path:
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.sendFile('index.html');
});
app.get('/report', function(req, res){
res.sendFile('report.html', { root: path.join(__dirname, './public') });
});
app.listen(8000);
I want to serve a single html page using express 4. It was used to possible with previous versions of Express but now it tells me "No default engine was specified and no extension was provided". Many thanks in advance.
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var router = express.Router();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static( path.join(__dirname, 'public')));
router.get('/', function(req, res) {
res.render('public/main.html');
});
module.exports = app;
library info below
"dependencies": {
"express": "~4.9.0",
"body-parser": "~1.8.1",
"cookie-parser": "~1.3.3",
"morgan": "~1.3.0",
"serve-favicon": "~2.1.3",
"debug": "~2.0.0",
"jade": "~1.6.0"
},
Below is the same example using Express 3 and it works as I would expect.
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get("/", function (req, res) {
res.sendfile('public/main.html');
});
module.exports = app;
Below is the correct way for serving a static html from Express 4. Thanks to E_net4 and NarendraSoni for their answers (1 and 2). For it to work you have to avoid using Express' router i.e. express.Router().get('/') as it will invoke the Express application's template engine.
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static( path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.sendfile('public/main.html');
});
module.exports = app;
res.render would invoke the Express application's template engine, but you haven't specified one.
Express provides a sendFile function in the response object, which allows you to send static page files without passing through a template engine.
var router = express.Router();
router.get('/', function(error, res) {
var options = {root: __dirname};
res.sendFile('something.txt', options, function(error) {
if (error) {
res.writeHead(500);
res.end();
}
});
});
There's something else that looks fishy in your code. You have created a router, but you didn't show where it was included in your application. It may be happening that some other middleware that relies on a template engine is intercepting the request.
app.use('/', router);
Also note that you do not need to create a new router in this case. An Application already behaves like a Router.
You are doing everything right, except that there is a very minor mistake. :)
edit your route definition as :
app.get('/', function(req, res) {
res.sendFile('main.html');
});
Now since you have already included :
app.use(express.static(path.join(__dirname, 'public')));
so you don't need to append public with your main.html.
That's it, enjoy, your code should work now.
If you just need to serve one file, you can replace your router with:
var fs = require('fs');
router.get('/', function(req, res) {
fs.readFile('public/main.html', function (err, html) {
res.writeHeader(200, {"Content-Type": 'text/html'});
res.write(html);
res.end();
});
});
Techically speaking, if you only want to serve static html files, you only need this line:
app.use(express.static( path.join(__dirname, 'public')));
meaning that if you were to GET /main.html from your root directory, it would be statically served without having to type any further code.
By using:
app.get('/', function(req, res) {
res.sendFile('main.html');
});
You are using routes that are defined for the root of the express application, instead of the Router(), as explained in the express docs here:
A route method is derived from one of the HTTP methods, and is attached to an instance of the express class.
The following code is an example of routes that are defined for the
GET...methods to the root of the app.
// GET method route
app.get('/', function (req, res) {
res.send('GET request to the homepage');
});
So what's happening here is that you are using routes defined for the root of the express application, instead of routes defined for the express.Router().
If you wanted to use the Router() to route things the same way, you could try code like this:
//app.use(express.static(path.join(__dirname, 'public')));
var router = express.Router();
app.use('/', router);
/* GET home page. */
router.get('/', function(req, res) {
res.sendFile(__dirname + '/path/to/file.html');
});
So, you do not have to avoid using the express.Router(), you just have to use routes from the root of your express app, OR routes from the express.Router() in a slightly different way
I am trying to make az ExtJS application with a Node.js server. My server code currently looks like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
When I open localhost:3000 in a browser, the html file is load, but not correctly. Checking in firebug I see that itt cannot find the linked files in html. For example
"NetworkError: 404 Not Found - http://localhost:3000/ext-4/ext-debug.js".
This is quite logical, since the file doesn't exist on that URL. My question would be how to fix this issue, so it could find every single linked file on my filesystem.
I'm clearly doing something wrong or missing something, I am totally new in node.
Doesn't look like you're configuring Express' static file handler.
Try adding this code:
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
It would go right after var app = ... like this:
var express = require('express');
var app = express();
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
And then place your static files under the ./public directory.
You'll want to use some static middleware such as: http://www.senchalabs.org/connect/static.html
note express inherits connect so you can
app.use(express.static(filedir));
Or the full thing:
var express = require('express');
var app = express();
app.use(express.static(filedir));
app.get('/employees', function(req, res){
console.log("hello");
res.send("hello");
});
app.listen(3000);