ExpressJS redirect index.html - javascript

JS,
I have an express app with some routes. When my router doesn't match any route it will display index.html instead of going to route '/*' and redirect to a specific route.
I don't understand why my router doesn't go to app.get('/*') because when I type https://my-domain.com I want to be redirect to https://my-domain.com/test?id=1.
Maybe I can do something with express-static but I don't know how.
And if I name my file home.html instead of index.html it's work perfectly.
Here is a small piece of my code :
const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();
const bodyParser = require("body-parser");
const ejs = require('ejs');
const csrf = require('csurf');
const port = 3080;
let csrfProtection = csrf({ cookie: true })
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(csrfProtection);
app.engine('html', ejs.renderFile);
app.set('view engine', 'html');
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
res.status(403).json({error: "Invalid CSRF Token"});
})
app.post('/roles', csrfProtection, (req, res) => {
/*...*/
});
app.get('/test', csrfProtection, (req, res) => {
/*...*/
});
app.all('/*', csrfProtection, (req,res) => {
if(Object.keys(req.query).length == 0) {
res.redirect("https://my-domain.com/test?id=1");
}
res.render(path.join(__dirname + '/index.html'), {csrfToken: req.csrfToken()});
});
app.listen(port, () => {
console.log(`Server listening on the port::${port}`);
});
My files structure is :
home
static
css
js
index.html
index.js

At the request for https://my-domain.com, write res.redirect('/foo/bar'), where /foo/bar is the url you want to redirect to.
See Official Documentation For res.redirect(): http://expressjs.com/en/api.html#res.redirect

Related

Express throws path must be absolute or specify root to res.sendFile when I use react router's redirect in react app bild

I serve a react-app built version in express, when I login it should redirect and show me another page. However, when I redirect to the right url I got this error path must be absolute or specify root to res.sendFile
How can I solve it?
Why can't I see other pages other than root?
Here is the code in express:
const app = express();
const portApp = 3003;
app.use(cors());
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(express.static(path.join(__dirname, "build")));
app.use(express.static("public"));
app.get("/attendances", (req, res, next) => {
res.sendFile(path.join(__dirname, "build", "index.html"));
});
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "build", "index.html"));
});
app.listen(portApp, () => {
console.log(
`Attendance list App is listening at http://localhost:${portApp}`
);
});

Node JS, Express & Pug Confusion - links / routes

I have Node.js, Express and Pug installed, and thought I was doing an MVC application. However, while I want my frontend pages to be (home, about, contact, login) with (snippets of data to connect to the backend) I can create these with pug (under views).
Wouldn't it be much faster to do these pages as static under my public folder with a stylesheet attached? Of course, I believe they would then need to be compiled into HTML for these to work I.
All I want to be able to do is create navigation that links these pages simply in pug, however, when running NPM I keep getting 404 errors (despite it working this morning).
If I can do this easily with pug, and just put a link, then why am I creating routes on the backend? Can someone please clarify this?
Pug (Sep nav file)
nav
a(href="/") Home
a(href="about") Framework
a(href="contact") Pricing
a(href="login") Support
Express Routes
app.get("/about", (req, res) => {
res.render("about");
});
app.get("/contact", (req, res) => {
res.render("contact");
});
app.get("/login", (req, res) => {
res.render("login");
});
app js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// View Engine ----------------------------
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Routes
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.get("/about", (req, res) => {
res.render("about");
});
app.get("/contact", (req, res) => {
res.render("contact");
});
app.get("/login", (req, res) => {
res.render("login");
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I've used Django before and despite its MVT (its very similar) but a lot simpler I think and I was able to do e.g %link% to insert it into the HTML page.

node js express app.get and app.post does not work

i wrote a code sample for express js and it is working but when I use app.post or app.get instead of app.use the code does not work and the ide (webstorm) does not recognize the app.post or app.get too
is it replaced with something in the newer versions of express or something?
here is my code:
const express = require('express');
let app = express();
app.use('/addp',(req,res,next)=>{
res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({extended:true}));
//next line does not work
//if I use app.use it will work fine
app.get("/product",(req,res)=>{
console.log(req.body);
res.redirect('/');
})
app.use('/',(req,res)=>{
res.send("<h1>done</h1>")
})
app.listen(3000);
Your code is working fine. For the print body, you should have to use bodyParser in express js.
const express = require('express');
let app = express();
var bodyParser = require('body-parser')
app.use('/addp', (req, res, next) => {
res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({ extended: true }));
app.use(
bodyParser.json({
limit: "250mb"
})
);
app.use(
bodyParser.urlencoded({
limit: "250mb",
extended: true,
parameterLimit: 250000
})
);
app.get("/product", (req, res) => {
res.send("Get Request")
})
app.post("/product", (req, res) => {
console.log("-------------")
console.log(req.body);
console.log("-------------")
res.send("Post Request")
})
app.use('/', (req, res) => {
res.send("<h1>done</h1>")
})
app.listen(3000);
It is this:
app.route('/product/').get(function (req, res) {
If u want to add multiple routes let's say api, u will do this:
In some module api.js:
const apiRoutes = express.Router();
apiRoutes.get('/some', () => {});
apiRoutes.post('/some', () => {});
Then let's say your server:
app.use('/api', apiRoutes);

What is the problem with router division in express? (React)

[app.js]
onCreate = async (event) => {
event.preventDefault();
const clubData = new FormData(event.target)
console.log(clubData);
const post = await axios.post('/club', {
method: 'POST',
body: {
name : 'name',
intro : 'intro'
}
}).then(response => {console.log(post)})
}
This is when the router is not division.
[server.js]
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 4000;
app.use(express.static(path.join(__dirname, '..', 'public/')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.post('/club', function(req, res, next) {
res.send({ test: 'test'});
})
app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
app.listen(PORT, () => {
console.log(`Check out the app at http://localhost:${PORT}`);
});
At this point, we were able to see data coming over from the developer window at Chrome.
However, after splitting the router, an error occurs.
[server.js]
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 4000;
var clubRouter = require('./router/clubRouter.js');
app.use(express.static(path.join(__dirname, '..', 'public/')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use('/club', clubRouter);
app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
app.listen(PORT, () => {
console.log(`Check out the app at http://localhost:${PORT}`);
});
[clubRouter.js]
const router = require('express').Router();
const controller = require('../controller/clubController');
router.post('/club', function(req, res, next) {
res.send({ test: 'test'});
})
module.exports = router;
An error occurs at this time.
(POST http://localhost:3000/club 404 (Not Found))
I've now created a project with a react-app-create and webpack.config.Added the code to dev.js file.
devServer: {
port: 4000,
open: true,
proxy: {
"/": "http://localhost"
}
},
The code was also added to the package.json file .
"proxy": "http://localhost:4000"
The clubRouter is mounted on path /club
That means any /club* requests will be handled over to clubRouter
The clubRouter further registers a controller on path /club that sends the response { test: 'test'}
So,
The complete path would now be => /club/club
In your React app, try this change and it would work:
const post = await axios.post('/club/club', { ... })
If you think the path is not how you want, you can register the controller in the clubRouter as follows:
router.post('/', function(req, res, next) {
res.send({ test: 'test'});
})
That way, you would be able to get hit it with the old path as:
const post = await axios.post('/club', { ... })

Routing an Invalid Request to a 404 Error Page

I'm trying to build a server that user will be able to enter these valid paths:
localhost:9090/admin
localhost:9090/project1
and in case the user enters anything else invalid such as these the user will be redirected to root and then to the default path localhost:9090/404.html:
How do I do it?
this is my code:
app.js
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})
route.js
'use strict';
var express = require('express');
var app = express();
var router = express.Router();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index');
});
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
res.render('c:/monex/myprojects/' + name +'/index');
});
app.use(function(req, res, next){
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
});
module.exports = router;
Expressjs has a pretty cool way of handling errors and routing them.
1/ To Confirm if project exists
We use the filesystem module to confirm if it exists, using the access API, you can read more on the module at https://nodejs.org/dist/latest-v6.x/docs/api/fs.html
var fs = require('fs') // We'll need to ask the filesystem if it exists
var projectname = 'myfolder';
// Excerpt from your code, but Modified
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
fs.access(name, fs.constants.F_OK, function(err) {
if(!err) { // directory exists
res.render('c:/monex/myprojects/' + name + '/index');
return;
}
// Directory does not exist
next({statusCode: 404});
})
});
2/ To route the error properly
From the above code, we said anytime directory does not exist in nodejs, call next with an error object, i.e next(err), the difference between next() and next(err) is that there are two types of middlewares in expressjs, the first is:
app.use("/", function(req, res, next) {})
while the second is
app.use("/", function(err, req, res, next) {})
The difference between the two is that, the first one is a normal middleware that routes requests through. But the second is called a error handling middleware. Anytime that next function is called with an argument, express jumps to route it through error handling middlewares from there on. So, to solve your problem.
You will want to solve this at the app level so that all across all routers, you can have 404 pages delivered.
In app.js
function Error404(err, req, res, next) {
if(err.statusCode === "404") {
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
}
// YOu can setup other handlers
if(err.statusCode === "504") {}
}
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(Error404);
REFERENCES
http://expressjs.com/en/guide/error-handling.html
https://www.safaribooksonline.com/blog/2014/03/12/error-handling-express-js-applications/
https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
Try changing the signature of your 404 handler function
Express will use it as an error handler of just add change function parameters to: (err, req, res, next)
I also got it fixed by adding this to my app.js
app.use(function (err, req, res, next) {
res.render('c:/monex/505.html', { status: 500, url: req.url });
})
making it look like this
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(function (err, req, res, next) {
res.render('c:/monex/404.html', { status: 404, url: req.url });
})
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})

Categories

Resources