Is there a way to attach JSON Web Tokens to an HTML form POST request?

56
April 22, 2019, at 04:00 AM

I'm building a blog using node.js (no Express) where users can comment on posts. I require users to log in before they can comment, so I'm using JSON Web Tokens (created via the jsonwebtoken node module) to authenticate their log in status. When they successfully log in, a cookie containing the JWT is added to the page response header, like this:

res.writeHead(302, {"Set-Cookie": `jwt=${MYTOKENISHERE}; max-age=9000; HttpOnly`, 
Location: "/blog/blog.html"
}); 
res.end();

When I inspect the webpage's cookies in my browser, I can see the encoded JWT - so far, so good:

Link to screenshot: https://i.ibb.co/MBzw5jX/cookies.png

The problem comes when a logged-in user tries to post a comment. I'm handling this with a POST request via an HTML form, but for some reason the JWT doesn't appear in the request object that reaches my server/router. Here is a snippet from my router code:

const cookie = require('cookie');
if (method === "POST") {
    if (request.url.includes("/create/comment")) {
        let cookies = cookie.parse(request.headers.cookie);
        console.log("COOKIES :", cookies);
        }
    }
//Expected console.log() output: 
COOKIES: { 
    jwt: [THE ENCODED JWT STRING],
    _ga: 'GA1.1.1615891668.1553812077', // random google analytics cookie
    gid: 'GA1.1.1919987325.1555742391' // random google analytics cookie
}
// Actual console.log() output: 
COOKIES: { 
    _ga: 'GA1.1.1615891668.1553812077', // random google analytics cookie
    gid: 'GA1.1.1919987325.1555742391' // random google analytics cookie 
}

As you can see, the JWT is missing. I have tried replacing the HTML form request with an XmlHttpRequest from the DOM, but I still get the same result. The JWT appears fine in GET request headers, I'm only having this issue with POST requests.

What is the best way to pass an encoded JSON Web Token string from the client to the server?

READ ALSO
Execute SQL query on HTML form element ( Dropdown ) onchange event

Execute SQL query on HTML form element ( Dropdown ) onchange event

I have trying to execute SQL query when we change the dropdown valuesSince we can't execute it using JavaScript , How can we do that

29
Position of div children get wrong because of scale transform on div parent

Position of div children get wrong because of scale transform on div parent

I'm working on a react app where there is two columns face to face, each columns has rows insideEach rows of differents columns can be connect by one or many lines

51
Is it possible to add a two dot in a variable name in Javascript?

Is it possible to add a two dot in a variable name in Javascript?

i want to create a variable like this in javascript

26
Load images by mouseclick

Load images by mouseclick

I am trying do load apng file with p5

20