javascript - How to set headers while requesting a page in nodejs? - Stack Overflow

I saw many tutorials on jwt authentication but every video maker uses Postman to show what's happe

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.

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.

Share Improve this question asked Mar 29, 2020 at 20:26 sat_yam_sat_yam_ 111 silver badge4 bronze badges 2
  • Are you trying to make http requests or want you to secure routes on a server with JWTs ? – Marc Commented Mar 29, 2020 at 20:41
  • Actually want to send headers to access secure routes – sat_yam_ Commented Jun 27, 2020 at 19:10
Add a ment  | 

5 Answers 5

Reset to default 2

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

In vanilla nodejs:

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

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/dist/latest-v12.x/docs/api/http.html#http_http_request_options_callback

Something like that:

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

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')
});

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 remend that you use a library like **axios*.

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

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745320819a4622435.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信