Express.static is not serving login page - javascript

I set the homepage to login.html, but why does the homepage be index.html?
I tried to delete index.html. It turns out that the web shows login.html so I was wondering.
app.js
const express = require('express')
const bodyParser = require('body-parser');
const path = require('path');
const app = express()
const PORT = process.env.PORT || 3000
express.static('public')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,'/public/login.html'))
})
app.listen(PORT, () => {
console.log(`Server is running on port : ${PORT}`)
})
public folder
public
---> css
---> img
index.html
login.html

In regards to serve-static, the documentation says:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
http://expressjs.com/en/resources/middleware/serve-static.html
In your example, you can disable this default behavior by setting the "index" option to "false":
app.use(express.static("public", { index: false }));
There is also an option to pass an array (as mentioned in the documentation):
app.use(express.static("public", { 'index': ['login.html', 'index.htm'] }));

Related

How am I supposed to use app.METHOD in Node.js?

so I'm trying to make a simple "route system", that would handle requests and send them to a certain controller.
The problem is that I can't even handle any route, because I get
Cannot GET /
error in response.
app.js
const express = require('express')
const router = require('./routes/routes')
const app = express()
const port = 3000
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
router.load()
app.listen(port, () => {
console.log(`Waiting on :${port}`)
})
routes.js
const express = require('express')
const app = express()
// Route config
const routes = {
['/']: {
controller: 'index',
method: 'get'
},
}
// Load routes
const load = () => {
for (const route in routes) {
app[routes[route].method](route, (req, res) => {
// Do something
})
}
}
exports.load = load
You don't use your router file in app.js, try that:
app.js
const express = require('express')
const router = require('./routes/routes')
const app = express()
const port = 3000
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
app.use('/', router);
router.load()
app.listen(port, () => {
console.log(`Waiting on :${port}`)
})
routes.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) { res.send({ success: true }); });
module.exports = router;
It's useless and unreadeable create an array whit your all your routes.
My suggestion is to try use command by terminal express my_app for generate the base structure and try to use it or at least read for see how it's work.
You seem to be lacking the context for how the routing system works within Express.
As a starting point, please create a project with the below structure, and try creating your own route to ensure you have a grasp on how to utilize them properly.
Create a new project folder
cd into the project folder from within your terminal
run npm init -y
Run npm i express dotenv
Create a file named app.js in the root of your project folder and place the below code inside of it:
require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json({limit: '30mb', extended: true}));
app.use(express.urlencoded({ extended: true }));
app.listen(process.env.PORT || 3000, () => {console.log('Server successfully started')});
app.get('/', (req, res) => {
return res.send('Hello, World!');
});
Create a new folder named routes
Create a new file named test.js and place it inside of the routes folder
Place the below code in the test.js file.
const router = require('express').Router();
router.get('/', (req, res) => {
return res.send('Hello from your custom route!');
});
module.exports = router;
Go back into your app.js file and add the below lines of code to the bottom of the file
const testRoute = require('./routes/test');
app.use('/test', testRoute);
In your terminal, run node app.js
Make a GET request to http://localhost:3000/test by navigating to it with your browser, or by using a REST client, such as Postman.
Once you have completed these steps, you should understand the basic concept of Express routing.
You can use the router combined with Express Middleware to re-route your user to the proper controller based on the endpoint they are trying to access / the data they are trying to send.
Please test with this code
const express = require('express')
const app = express();
app.get('/', (req, res) => {
res.json({"message": "Welcome! it's working"});
});
The complete code is here on Github

Nodejs page (HTML) conversion, like how to changing the page when I click a button in main page jump to login page?

In my router code, I have something like below. In my main page, I have a button to jump to login page, that is work with out nodejs, but after I connect the node.js code, only show me the main page, if I click the login button, the page will show be that Cannot GET /LoginPage.html. How to fix that?
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.render('HomePage.html', {
title: 'Hello World'
})
})
router.get('/login', (req, res) => {
res.render('LoginPage.html', {
title: 'Hello World'
})
})
In the app.js code:
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const multer = require('multer');
const GridFsStorage = require("multer-gridfs-storage");
const path = require('path')
const cors = require('cors')
const crypto = require("crypto");
const favicon = require('serve-favicon')
const app = express();
const User = require('./models/user')
const router = require('./router')
app.engine('html', require( 'express-art-template'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static(__dirname + '/public'))
app.use('/node_modules/', express.static(__dirname + '/node_modules'))
app.use(cors());
app.use(router)
app.listen(4001, (req, res) => {
console.log('port xxxx')
})
In the HTML code, just click the button, and jump to Loginpage.html
Login
A couple of things,
you have 2 same endpoints router.get('/',
So change the second route to something like router.get('/login',
you should access your login page now on /login
You are getting Cannot GET /LoginPage.html because there is no route LoginPage.html in your backend
First thing is the way you defined the routes is wrong as you have 2 same end points.Try to change the login endpoint as /login in your .js file.
You need to change the html file also as you are trying to call directly the html file not the api end point /login.You need to call to the node backend endpoint which renders the desired html file.
not the direct reference to html file.
Edit 1:
Please do the following:
Change your app.js file like below:
const express = require('express');
const app = express();
const router = require('./router');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
app.engine('html', require('express-art-template'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('', express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use(router);
app.listen(4001, (req, res) => {
console.log('port 4001');
});
And the router.js to like this
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.render('index.html', {
title: 'Hello World',
});
});
router.get('/login', (req, res) => {
res.render('login.html', {
title: 'Hello World',
});
});
module.exports = router;
And create a public folder and create 2 html files index.html and login.html. Your app structure should be like below:
--public
-------+ index.html
-------+ login.html
-- app.js
--router.js
--package.json
I tried this it worked for me. Change the variables and other file names as per your need. I guess your folder structure and the way you are rendering is wrong.Hopefully it should work.

how to serve a directory with express?

I would like to create a simple express server that sends a directory like the image following:
Browser directory picture
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'shaders')));
app.use('*', (req, res) => {
res.sendFile((path.join(__dirname, 'shaders')));
});
const PORT = 3000;
app.listen(PORT, () => {
console.log('listening on port ', PORT);
});
This code displays Cannot GET / in the browser window.
Using a library
There are libraries that already do this for you, for example serve-index.
Doing it yourself
This is a modified version of your code to show file content or list the files/directories in a directory. I've added some comments to explain what's happening, but feel free to ask more questions if something is not clear.
const express = require("express");
const path = require("path");
const fs = require("fs");
const app = express();
const listingPath = path.join(__dirname, "shaders");
app.get("*", (req, res) => {
// Build the path of the file using the URL pathname of the request.
const filePath = path.join(listingPath, req.path);
// If the path does not exist, return a 404.
if (!fs.existsSync(filePath)) {
return res.status(404).end();
}
// Check if the existing item is a directory or a file.
if (fs.statSync(filePath).isDirectory()) {
const filesInDir = fs.readdirSync(filePath);
// If the item is a directory: show all the items inside that directory.
return res.send(filesInDir);
} else {
const fileContent = fs.readFileSync(filePath, 'utf8');
// If the item is a file: show the content of that file.
return res.send(fileContent);
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log("listening on port ", PORT);
});
You can use this as a base to make a template that includes links to the files/directories, to include a link to the parent directory, to show more meta data ...
You can use a static folder for sharing or fetch files via GET request.
app.use(express.static(path.join(__dirname, 'shaders')));
This code displays Cannot GET / in the browser window.
Sending a GET to / will fallback to your app.use * as you don't have a route defined. It's not clear what this should do as you're returning a directory instead of a file, which isn't going to work.
If you'd like to access a specific file, you need to request it directly as localhost:3000/shaders/xxx, etc. The use of express.static appears to be correct.

Get method not able to be detected by the Node.js

I am new to node and express js.Today I am learning and I have initialized node server as:
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const PORT = 3000
const api=require('./routes/api')
const app = express()
app.use(bodyParser.json())
app.use(cors())
api.use('/api',api)
app.get('/', function(req, res) {
res.send('Hello from server')
})
app.listen(PORT, function(){
console.log("Server running on localhost:" + PORT)
});
I have created a folder routes inside server folder and there is api.js file which has GET method to test, whether the api is working or not.Inside api.js I have,
const express = require('express')
const router=express.Router()
router.get('/', (req, res) => {
res.send('from Api Route');
})
module.exports=router
I type node server and it is displaying me :
Server running on localhost:3000
But,when I try to get the url: http://localhost:3000/api,it is displaying me:
And,in api.js file in the arrow function sublime is showing me error in red marker as:
Replace api.use('/api',api) with app.use('/api',api)

Unexpected Token . when running server.js

I'm currently writing a web application with the MEAN stack, and am testing to see if my nodejs server is working. Here's my server.js:
// server.js
'use strict';
// modules =================================================
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
// configuration ===========================================
// config files
const db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to mongoDB
// (uncomment after entering in credentials in config file)
// mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('App running on port ' + port);
// expose app
exports = module.exports = app;
I currently have it redirecting all routes to my index.html file to test to make sure my views are working. Here's my routes.js:
// models/routes.js
// grab the user model
var User = require('./models/user.js');
module.exports = {
// TODO: Add all routes needed by application
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
However, when I try to run node server.js, it gives me this error:
/home/hess/Projects/FitTrak/app/routes.js
app.get('*', function(req, res) {
^
SyntaxError: Unexpected token .
Does anyone have any idea what's causing this? I checked and all my braces and parentheses are all closed and written correctly.
As Jose Hermosilla Rodrigo said in his comment, you're declaring the object literal module.exports wrong. It should look like this instead:
module.exports = function(app) {
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
just try this code...
// models/routes.js
var express=require('express');
var app=express();
// TODO: Add all routes needed by application
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
module.exports = route;
server.js
'use strict';
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var route=require('./models/route.js');
const methodOverride = require('method-override');
// configuration ===========================================
// config files
const db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to mongoDB
// (uncomment after entering in credentials in config file)
// mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('App running on port ' + port);
app.use('/',route);
If you are using MEAN stack I would suggest you to use express own router middleware to handle all your routes. Just include.
var router = express.Router();
//use router to handle all your request
router.get(/xxx,function(req, res){
res.send(/xxxx);
})
// You may have n number of router for all your request
//And at last all you have to do is export router
module.exports = router;

Categories

Resources