Send an external API token with request in Node.js

Asked

Viewed 82 times

0

I’m new to Node.js, I have a question maybe easy to resolve... I have an Node.js application that communicates with external API in php, send and receive information through tokens, and I found a dilemma when using the request, I can send the token if I put double quotes but if I put the token variable the external API does not recognize. I am Using request, jsonwebtoken and mysql, interesting that when sending a variable with less characters works normally. I tried toString, concatenation, and nothing. Below is an excerpt of the code:

    const mysql = require('mysql');
    const request = require('request');
    const jwt = require('jsonwebtoken');

                connection.query(tok.script, function (err, rows, fields2, res) {
                    if(err)
                        resjson = err;
                    else
                        resjson = rows;
                    cliente = {cliente:tok.sub};
                    const unirjson = Object.assign(cliente, resjson);
                    const token= jwt.sign(unirjson, 'senha');
                    const options2 = {
                        uri: 'https://meusite.com.br/api/semaforo',
                        method: 'POST',
                        json:{"token":token}
                    }
                    console.log(options2);
                    request(options2, function (error, response, body) {
                        if (!error && response.statusCode == 201) {
                            console.log("Deu Erro: " + error);
                        }
                        if (!error && response.statusCode == 200) {
                            console.log("Deu Certo: " + body);
                        }
                    }); 
                });
  • You need to actually send the content of the token or it is for authentication in your external api?

  • I decided to send the token in the body, for more security, in addition to authentication with basic auth, since it will be the answer of a query there is a local bd.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.