George Salamanca
George Salamanca

Reputation: 180

cannot set header when using express hbs render

I am trying to insert a token into the response header of a post route just before the view-engine-hadlebars renders.

This is the post route that I want to set up the haeder in:

app.post("/signup", (req, res) => {


let email = req.body.usremail;
let password = req.body.password;


var user = new User({
    email,
    password
})
user.save().then(() => {
    return user.generateAuthToken();
}).then((token)=>{


    res.set('x-auth', token);
    res.render("project.hbs", {
        paragraph: `Welcome ${email}. What would you like to do?`,
        button1: "New poll",
        button2: "See your polls",
        button3: "See all polls",
        link1: "/newpoll",
        link2: "/yourpolls",
        link3: "/allpolls",
        pie: true,
        two: true
    })
}, (e) => {
    console.log(e.message);
})

})

This is the get route that I want to receive the header in:

loginRouter.get("/newpoll", authenticate, (req, res) => {
console.log("newpoll/get:",req.header("x-auth"));

   res.render("project.hbs", {
    paragraph: `Enter your poll question and answers then submit`,
    quessubmit: true,
    method: "post",
    action: "/newpoll",
    ques: true
})
})

the get route is saying it's undefined. Any thoughts are much appreciated.

Upvotes: 0

Views: 639

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40394

That is not how headers work. When you do: res.set('x-auth', token); on /signup route, you're setting a response header, that header will be sent to the client, but won't persist to other requests.

When the user clicks on the link, and goes to /newpoll, there is no possible way to send a custom a HTTP header through the a element, so your code won't work.

What you're looking for is a cookie, that will be set on /signup and can be retrieved on any other route.

const cookieParser = require('cookie-parser');
const express = require('express');

const app = express();
app.use(cookieParser());

app.post("/signup", (req, res) => {
    /* ... */
    res.cookie('x-auth', token);
    /* .. */
});

loginRouter.get("/newpoll", authenticate, (req, res) => {
    console.log("newpoll/get:",req.cookies["x-auth"]);
});

Take a look at res.cookie documentation, to learn how to set secure options.

NOTE: I do not know what your method authenticate does, or how are you authenticating the users, but you should probably check whether x-auth cookie is set or not there.

Upvotes: 2

Related Questions