Node js 404 and angular url refresh conflict - javascript

I am making an Nodejs and angular js app. I had to make a page loads when someone type on url and enter it. It worked fine until I also made a script to redirect to 404 error page. Now the problem is with both script only one of the criteria works. When 404 redirection works i cannot go to the page with url typed on browser and when that works then 404 page is redirected to index. html.
Here are the two scripts that I have use.
app.use(function(req, res) {
res.render('404', {layout: false, title: '404: File Not Found'});
});
app.use('/*', function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
Am I doing anything wrong over here. Beside this I also have my general routes which works fine in angular app when I click it from navigation.

Put 404 handler code at end (It must be last route)
Use your code like this:
app.use('/*', function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.use(function(req, res) { //put this at end
res.status(404);//add this line for setting 404 status
res.render('404', {layout: false, title: '404: File Not Found'});
});

The 404 route must be the last route.

Put this before your 404 route:
app.use('/reload/reload.js', express.static('node_modules/reload/lib/reload.js'));

Related

Problems while loading CSS tied to an EJS page while using res.redirect()

So I'm using express with ejs where I've this as my base route
router.get("/", productsData.getProducts);
where productsData is from my controllers page and this is the code there
exports.getProducts = (req, res, next) => {
res.render("shop/index", { pageTitle: "Shop", path: "/" });
};
network tab in the developer tools show the css files werent loaded
On checking it I saw net::ERR_EMPTY_RESPONSE on the request for the css files.
If I reload the page it works fine and the css are loaded. This is the code for the CSS import.
<link rel="stylesheet" href="/css/main.css" />
The only thing that goes wrong is when It redirects here
exports.postAddProduct = (req, res, next) => {
const product = new Product(req.body.title);
product.save();
res.redirect("/");
};
Can anyone tell whats going wrong, is it with something with res.redirect() or something else?
Actually the code was good, I was saving the form uploads in a file in the directory same as my code while using nodemon, which was watching the whole code. So everytime I submitted the form, it restarted the server because of which this issue occurred.

URL rewriting not working in Express 4.14.1

I've found in quite a few SO posts that in order to rewrite a URL in Express 4 I would do something like the following:
router.use('/one/:someId', (req, res, next) => {
req.url = `/two/${req.params.someId}`;
next();
});
router.get('/one/:someId', (req, res) => {
res.send("reached /one/:someId");
});
router.get('/two/:someId', (req, res) => {
res.send("reached /two/:someId");
});
But when I try this, not only does the URL does not change to my expected "/two/some integer" and stays being "/one/some integer" but it gets to the 404 - Not Found page I have set up in my app file.
This routes are in a router file and I have also tried setting the URL to:
req.url = `/routerPath/two/${req.params.someId}`;
but the result is exactly the same.
So what could I be missing?
Thank you.
You have to distinguish two kinds of redirects:
Internal redirects work on the server, without the client noticing. They are a convenience for your server programming and never necessary - you could always introduce a helper method that gets called by all endpoints.
HTTP redirects advise the client (e.g. a web browser) to go to a different URL. Since you expect the URL to change, that's the one you want.
Simply call res.redirect, making sure to encode special characters:
router.get('/one/:someId', (req, res) => {
res.redirect(`/two/${encodeURIComponent(req.params.someId)}`);
});
router.get('/two/:someId', (req, res) => {
res.render("reached /two/:someId");
});

How do I call a invoke an ajax get request from client side, using Node/Express?

I have a file shuffleRoute.js where I define this:
router.get("/shuffle?jokers=false", function (req, res) {
cards['a','b','c'];
let shuffledCards = _.shuffle(cards);
res.status(200).send(shuffledCards);
});
I have an index.js where I define:
app.get("/v1/game", require("./routes/shuffleRoute.js"));
I have a game.html where onload I need to do an ajax request to get the shuffled cards. How do I do that?
doing this
$.get( "/v1/game", function(res) {
console.log(res);
});
does not work.
I am getting this error:
jquery-2.2.4.min.js:4 GET localhost:8080/v1/game 500 (Internal Server Error) –
I was using morgan to log things in the server which was incorrectly done.
However, commenting that out gives me this error.
jquery-2.2.4.min.js:4 GET http://localhost:8080/v1/game 404 (Not Found)
May be wrong but i see routes problem here.
When you define routes for express use app.use
var myRoute = require('PathToYourRouteFile');
app.use("/v1/game", myRoute);
In route file. Im asuming you use express router you need to define something like this
youRuoterName.get('/', function(req, res, next) { })
This request will be succes when you go to localhost/v1/game.
If you want another one just do
youRuoterName.get('/shuffle', function(req, res, next) { })
Which will be succes when you go to /v1/game/shuffle.
In your example i see only one route /v1/game/shuffle which clearly not match /v1/game and im not even sure that rest of code works as expected.
So please read docs carefuly http://expressjs.com/en/4x/api.html#router.route
and all should work.
Hope this helps.

undefiend function using connect-flash middleware

In my app.js
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
and in my jade file I have
!= messages()
I open the page it says undefiend is not a function function. I already restarted my server, I don't know what's wrong.
If the != messages() causes the problem then the error must occur on the server while rendering the jade file. The jade compiler is povided with a data object that contains a message method.
This message method is provided with res.locals.messages and set with the express-messages call. From all I know up to now I would asume that you positioned the code above after you configured the route to page. Then the page is rendered before you set the message method. In that case reorder the app.use calls, so the route is defined at last.
Hope that help!

Nodejs and express are not able to locate resource file(CSS & JS file)

I'm try to use express to build a simple website.
everything it's works fine, until I decide to add a below code to catch 404 error
app.get('/*', function(req, res) {
res.render('404.ejs',{
title: 'PAGE NOT FOUND',
layout:'layout'})
});
after that, notice all internal CSS file and JavaScript recourse file, not able to load correctly, I figure out because those CSS and JavaScript file ref link it's not inside the routing configure. That why all route to page not found which catch by /*
so just want to know, what is correct way, I can catch the 404 errors and display my own customize page, and also no impact on all resource file loading. Thanks!
If you are using express, you should use error-handling middleware such as these examples:
// Routing and public files
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// Error-handling middleware
app.use(function(err, req, res, next) {
// Parse error
// Ex. if error = 500, render 500.jade page
// At the end
next(err);
});
// This is called on any page not in router.
app.use(function(req, res, next) {
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.render('error/404', { title: '404 Error.' });
return;
}
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
Refer to this For more information on Express error-handling.

Categories

Resources