Error: Can't set headers after they are sent - node.js

In my node app, I have routes called index and home. While trying to redirect from index to home route it throws the following error:
Error: Can't set headers after they are sent
Here is the code:
app.get('/index', function (req, res) {
res.redirect('/home');
})
app.get('/home', function (req, res) {
res.send('Welcome Home !!');
})

You can try replace '/index' with "/index". It works fine after that.

Related

Node Pug: Action attribute of form tag does not work properly when using variables

I have an index.pug page that is:
head
title My Title
body
form(method="GET", action='/#{redirect_url}')
button(type='submit') run foo
and in my app.js I have:
app.get('/', (req, res) => {
res.render('index', {
redirect_url: '/foo'
});
});
app.get('/foo', (req, res) => {
res.status(200).send('Foo triggered');
});
I am being redirected to http://localhost:3000/?#{redirect_url}.
I want to get redirected to http://localhost:3000/redirect_url?
It works fine when I do not use variables.
I have attached a screenshot for reference.
try
action=`${baseRoute}/${redirect_url}`

How can call a router from another current loaded route : Nodejs

I have loaded root route.
app.get('/', (req, res, next) => {
// loading an HTML page
});
We have loaded an HTML page where we have a submit button, submitting on this submit button, we load the "search" route.
This "/search" route is loading successfully, but we have to load some dynamic content and after fetching all data, we have to load another route like "/searchoutput"
When we call :
app.use('/searchoutput', router);
or
app.get('/searchoutput', router);
But nothing happens without any error.
Thanks
Kumar Anil
So, if I understood correctly, you could do something like this,
If it is a POST request:
app.post("/search", (req, res) => {
// some code
res.redirect("searchoutput");
});
app.get("/searchoutput" (req, res) => {
// some code
res.render("<your page>", { <yourResult>: <yourResult>);
});
If it is a GET request:
app.get("/search", (req, res) => {
// some code
res.redirect("searchoutput");
});
app.get("/searchoutput" (req, res) => {
// some code
res.render("<your page>", { <yourResult>: <yourResult>);
});
If you don't want to reload the page, you could use AJAX, calling onclick a function that receives data from express.

router.use middleware chain not working as expected?

I've the following middlewares:
injectParamMiddleware.js
module.exports = function(req, res, next) {
req.params.specialParam = 'specialValue';
next();
}
logParamMiddleware.js
module.exports = function(req, res, next) {
console.log(req.params.specialParam);
next();
}
SCENARIO 1
router.get('/resource/:resourceId',
injectParamMiddleware,
logParamMiddleware,
...MoreMiddlewares)
SCENARIO 2
router.use('/resource/:resourceId', injectParamMiddleware, logParamMiddleware);
router.get('/resource/:resourceId', ...MoreMiddlewares);
While running SCENARIO 1, I get specialValue logged in the console.
While running SCENARIO 2, I get undefined logged in the console.
I was expecting SCENARIO 2 to log specialValueas well.
Any help is really appreciated.
Thanks in advance.
EDIT: I'm using Express 4.14.0 and Node 6.10.3
Scenario 2 is causing an error 'by design' of express as the router is what creates params. It is getting overwritten
You can assign the var to another property in the app.use that will pass to the request
such as req.specialParam = 'specialValue'
app.param('/user/:name', (req, res) => {
req.specialParam = 'specialValue';
});
Other options are to modify the params wit the .param() method:
app.param('/user/:name', (req, res) => {});
or
app.route('/user/:name')
.all((req, res) => { ... console log here })
.get((req, res) => { ... })

Route with /:id returns 404 for client side javascript

I am using numerous routes in express and node, and for the routes that use an "/:id" at the end of the route, it returns 404 not found for the client-side javascript files.
this route works
app.route('/createPoll')
.get(function (req, res) {
res.render(path + '/public/createPoll.ejs', {
userID: "logged-in"
});
};)
this route does not find the javascript file
app.route('/deletePoll/:id')
.get(function (req, res) {
res.render(path + '/public/profile.ejs', {
userID: "logged-in"
});
};
They are both looking for the same common javascript files located in app/common and app/controllers. How to correct the path for the route with /:id?

Node Express return 404 custom message

I'm using NodeJS with Express and when an Endpoint is not found Express returns
I'd like to return a Custom 404 Message instead of the above image whenever an Endpoint is miss-typed.
I've tried adding the following to app.js
app.use(function (req, res, next) {
res.status(404).send("Sorry can't find that!")
})
But this just returns ALL endpoints with
Sorry can't find that!
You need to make that this the last 'route' in app.js
app.use(function (req, res, next) {
res.status(404).send("Sorry can't find that!")
})
The order your specify your routes is important.

Resources