Authorization missing or empty after setting Headers

I’ve been trying to add set the authorization in my headers after a user logs in, but no matter what I’ve tried, the authorization field is either empty or missing.

If I log in from my application on the web and log what I get like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>console.log("AccessTokenHere"); // I get the correct token
console.log("Logged in!");
res.header('Authorization', "Bearer " + accessToken);
console.log(req.headers);
</code>
<code>console.log("AccessTokenHere"); // I get the correct token console.log("Logged in!"); res.header('Authorization', "Bearer " + accessToken); console.log(req.headers); </code>
console.log("AccessTokenHere"); // I get the correct token
console.log("Logged in!");
res.header('Authorization', "Bearer " + accessToken);
console.log(req.headers);

This is what I get back:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{host: 'localhost:5001', connection: 'keep-alive', content-length: '48', cache-control: 'max-age=0', sec-ch-ua: '"Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"', …}
accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'
accept-encoding:'gzip, deflate, br, zstd'
accept-language:'en-CA,en;q=0.9,fr-CA;q=0.8,fr;q=0.7,en-US;q=0.6'
cache-control:'max-age=0'
connection:'keep-alive'
...
</code>
<code>{host: 'localhost:5001', connection: 'keep-alive', content-length: '48', cache-control: 'max-age=0', sec-ch-ua: '"Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"', …} accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7' accept-encoding:'gzip, deflate, br, zstd' accept-language:'en-CA,en;q=0.9,fr-CA;q=0.8,fr;q=0.7,en-US;q=0.6' cache-control:'max-age=0' connection:'keep-alive' ... </code>
{host: 'localhost:5001', connection: 'keep-alive', content-length: '48', cache-control: 'max-age=0', sec-ch-ua: '"Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"', …}
accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'
accept-encoding:'gzip, deflate, br, zstd'
accept-language:'en-CA,en;q=0.9,fr-CA;q=0.8,fr;q=0.7,en-US;q=0.6'
cache-control:'max-age=0'
connection:'keep-alive'
...

Authorization is nowhere to be seen.

Doing this on thunderClient though, I get an additional authorization:'' line.

I’m sending a post request through my login function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const express = require("express");
const appUser = express();
const User = require("../models/userModel");
const dotenv = require("dotenv");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const asyncHandler = require("express-async-handler");
const bodyParser = require("body-parser");
const mustache = require('mustache');
const path = require("path");
var engine = require('consolidate');
const http = require('http');
appUser.use(express.json());
appUser.set('views', __dirname + '/views');
appUser.engine('html', engine.mustache);
appUser.set('view engine', 'html');
appUser.use(bodyParser.urlencoded({ extended: true }));
const login = asyncHandler (async (req, res) => {
const email = req.body.email;
const password = req.body.Password;
console.log(`${email}, ${password}`)
if (!email || !password){
res.status(400);
throw new Error("Email or password not provided");
}
const user = await User.findOne({email});
if (user && (await bcrypt.compare(password, user.password))) {
const accessToken = jwt.sign({
user: {
username: user.id,
email: user.email,
id: user.id
},
}, process.env.ACCESS_TOKEN_SECRET,
{expiresIn: "30m"});
console.log("AccessTokenHere");
console.log("Logged in!");
res.header('Authorization', "Bearer " + accessToken);
console.log(req.headers);
res.redirect(302, "/home/user/userPAGE");
}
else {
res.status(400);
throw new Error("Email or Password is not valid");
}
});
</code>
<code>const express = require("express"); const appUser = express(); const User = require("../models/userModel"); const dotenv = require("dotenv"); const bcrypt = require("bcrypt"); const jwt = require("jsonwebtoken"); const asyncHandler = require("express-async-handler"); const bodyParser = require("body-parser"); const mustache = require('mustache'); const path = require("path"); var engine = require('consolidate'); const http = require('http'); appUser.use(express.json()); appUser.set('views', __dirname + '/views'); appUser.engine('html', engine.mustache); appUser.set('view engine', 'html'); appUser.use(bodyParser.urlencoded({ extended: true })); const login = asyncHandler (async (req, res) => { const email = req.body.email; const password = req.body.Password; console.log(`${email}, ${password}`) if (!email || !password){ res.status(400); throw new Error("Email or password not provided"); } const user = await User.findOne({email}); if (user && (await bcrypt.compare(password, user.password))) { const accessToken = jwt.sign({ user: { username: user.id, email: user.email, id: user.id }, }, process.env.ACCESS_TOKEN_SECRET, {expiresIn: "30m"}); console.log("AccessTokenHere"); console.log("Logged in!"); res.header('Authorization', "Bearer " + accessToken); console.log(req.headers); res.redirect(302, "/home/user/userPAGE"); } else { res.status(400); throw new Error("Email or Password is not valid"); } }); </code>
const express = require("express");
const appUser = express();
const User = require("../models/userModel");
const dotenv = require("dotenv");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const asyncHandler = require("express-async-handler");
const bodyParser = require("body-parser");
const mustache = require('mustache');
const path = require("path");
var engine = require('consolidate');
const http = require('http');
appUser.use(express.json());

appUser.set('views', __dirname + '/views');
appUser.engine('html', engine.mustache);
appUser.set('view engine', 'html');
appUser.use(bodyParser.urlencoded({ extended: true }));

const login = asyncHandler (async (req, res) => {
    const email = req.body.email;
    const password = req.body.Password;
    console.log(`${email}, ${password}`)
    if (!email || !password){
        res.status(400);
        throw new Error("Email or password not provided");
    }
    const user = await User.findOne({email});
    if (user && (await bcrypt.compare(password, user.password))) {
        const accessToken = jwt.sign({
            user: {
                username: user.id,
                email: user.email,
                id: user.id
            },
        }, process.env.ACCESS_TOKEN_SECRET,
        {expiresIn: "30m"});
        console.log("AccessTokenHere");
        console.log("Logged in!");
        res.header('Authorization', "Bearer " + accessToken);
        console.log(req.headers);
        res.redirect(302, "/home/user/userPAGE");
    }
    else {
        res.status(400);
        throw new Error("Email or Password is not valid");
    }

});

Which then is supposed to redirect to another page after verification that the token is good by this function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const asyncHandler = require("express-async-handler");
const jwt = require("jsonwebtoken");
const validateToken = asyncHandler(async (req, res, next) => {
let token;
let authHeader = String(req.headers['authorization'] || '');
console.log(req.headers);
console.log("boop");
if (authHeader.startsWith("Bearer ")) {
token = authHeader.split(" ")[1];
console.log("hey");
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
res.status(400);
throw new Error("User is not authorized");
}
req.decoded = decoded.user;
next();
});
if (!token) {
res.status(401);
throw new Error("User is not authorized or token is missing");
}
}
else {
res.status(401);
throw new Error("User is not authorized or token is missing");
}
});
</code>
<code>const asyncHandler = require("express-async-handler"); const jwt = require("jsonwebtoken"); const validateToken = asyncHandler(async (req, res, next) => { let token; let authHeader = String(req.headers['authorization'] || ''); console.log(req.headers); console.log("boop"); if (authHeader.startsWith("Bearer ")) { token = authHeader.split(" ")[1]; console.log("hey"); jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => { if (err) { res.status(400); throw new Error("User is not authorized"); } req.decoded = decoded.user; next(); }); if (!token) { res.status(401); throw new Error("User is not authorized or token is missing"); } } else { res.status(401); throw new Error("User is not authorized or token is missing"); } }); </code>
const asyncHandler = require("express-async-handler");
const jwt = require("jsonwebtoken");

const validateToken = asyncHandler(async (req, res, next) => {
    let token;
    let authHeader = String(req.headers['authorization'] || '');
    console.log(req.headers);
    console.log("boop");
    if (authHeader.startsWith("Bearer ")) {
        token = authHeader.split(" ")[1];
        console.log("hey");
        jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
            if (err) {
                res.status(400);
                throw new Error("User is not authorized");
            }
            req.decoded = decoded.user;
            next();
        });
        if (!token) {
            res.status(401);
            throw new Error("User is not authorized or token is missing");
        }
    }
    else {
        res.status(401);
        throw new Error("User is not authorized or token is missing");
    }
});

But we don’t even get there.
I’ve tried to use res.setHeader also, but that didn’t work and other posts with this similar issue didn’t help.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật