sat_yam_
sat_yam_

Reputation: 11

How to set headers while requesting a page in nodejs?

I saw many tutorials on jwt authentication but every video maker uses Postman to show what's happening and they pass on the header in the headers section while requesting a URL in Postman. I tried to do it with JavaScript but I was not able to do it.

I want to do jwt authentication but after token generation, I send it to client side to use it for further requests but I failed to do so after trying it a few times. I also tried to set req.headers in server side but it didn't do what I wanted to..

I want to set request headers for authentication of the form "Bearer {token}" for every request after token generation. How to do it with JS??

What I am most concerned about is that every tutorial does it with postman but they didn't show how they implemented it in their own app. I hope my question is clear.

Upvotes: 0

Views: 8930

Answers (5)

PDG
PDG

Reputation: 1868

If I understand correctly, you want to set the HTTP header on the client, in order to pass an authentication token to the server. I would recommend that you use a library like **axios*.

Using axios, once you receive the toke, set the header for every outgoing communication with the following line of code:

axios.defaults.headers.common['Authorization'] = "Bearer " + token;

This will set the authentication http header to the form you need.

Upvotes: 0

You can easily add header on your http request like that

it has been solved here Node.JS: How to send headers with form data using request module

Upvotes: 2

Mr Khan
Mr Khan

Reputation: 2292

First install jwt and express framework using npm then make a middleware file which will check if the tokek is set or not.

Middleware.js :

let jwt = require('jsonwebtoken');
const config = require('./config.js');

let checkToken = (req, res, next) => {
    let token = req.headers['authorization']; // Express headers are auto converted to lowercase

    if (token) {
        if (token.startsWith('Bearer ')) {  // Checks if it contains Bearer
            // Remove Bearer from string
            token = token.slice(7, token.length); //Separate Bearer and get token
        }

        jwt.verify(token, config.secret, (err, decoded) => {  //Inser the token and verify it.
            if (err) {
                return res.json({
                    status: false,
                    message: 'Token is not valid'
                });
            } else {
                req.decoded = decoded;
                next();
            }
        });
    } else {
        return res.json({
            status: false,
            message: 'Access denied! No token provided.'
        });
    }
};

Next, create a config file which will contain the secrets.

Config js:

module.exports = {
    secret: 'worldisfullofdevelopers'
};

Finally, create a token route which will create your token and after that the rest of the calls will be authenticated for that token.

Index.js :

const middleware = require('./middleware');
const jwt = require("jsonwebtoken");
const config = require('./config.js');

//Call token Route
app.use('/token', (req, res, next) => {

    //Generate Token
    let token = jwt.sign({ username: "test" },
        config.secret,
        {
            expiresIn: '1h' // expires in 1 hours
        }
    );

    //Send Token
    res.json({
        success: true,
        message: 'Authentication successful!',
        token: token
    });

});

//Add Authentication to all routes
app.use(middleware.checkToken);

//===> All the routes after middleware will be checked for token

app.use('/getUser', (req, res, next) => {; 
 console.log('do something')
});

Upvotes: 0

Marc
Marc

Reputation: 3874

In vanilla nodejs:

const uri = "http://example.com";

const options = {
    headers: {
        "Authorization": "Bearer ...."
    }
}

// require http/https lib
let req = require("http").request(uri, options, (res) => {

    const chunks = [];

    res.on("data", function (chunk) {
        chunks.push(chunk);
    });


    res.once("end", () => {

        // concat body chunks
        let body = Buffer.concat(chunks);
        console.log(body.toString());

    });


});

req.on("error", (err) => {
    console.log(err);
});

req.end();

https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_options_callback

Upvotes: 1

scuencag
scuencag

Reputation: 664

Something like that:

$.ajax({
  url: url,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("custom_header", "value");
  },
  success: function(data) {
  }
});

Upvotes: 0

Related Questions