将JSON响应从一个请求发送到另一个请求

时间:2021-04-25 16:02:10

I one question about request and respnse in expressJS. I my case in one request I post request to server and I get Bearer key in JSON, but this key is different in every session. And I have second request when I create order but I need this Bearer key to authorize transaction. And my question is poosible send data from one request to another? Bearer number I have to insert to 'Authorization' field. Please look on my code.

我在expressJS中有一个关于请求和respnse的问题。我在一个请求中的情况下我向服务器发送请求并且我在JSON中获得了Bearer密钥,但是这个密钥在每个会话中都是不同的。我创建订单时有第二个请求,但我需要此Bearer密钥来授权交易。我的问题是poosible将数据从一个请求发送到另一个请求?我必须在“授权”字段中插入承载号码。请查看我的代码。

router.post('/authorize', function(req, res){
request({
    method: 'POST',
    url: 'https://secure.snd.payu.com/pl/standard/user/oauth/authorize',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: "xyz"
},  function (error, response, body) {
        console.log('Status:', response.statusCode);
        console.log('Headers:', JSON.stringify(response.headers));
        console.log('Response:', body);
        res.send(body); //Here I get necessary Bearer key
  }
)}


router.post('/paynow', function(req, res){
   request({
method: 'GET',
url: 'https://secure.snd.payu.com/api/v2_1/paymethods/',
headers: {
    'Authorization': 'Bearer number'
}}, function (error, response, body) {
        console.log('Status:', response.statusCode);
        console.log('Headers:', JSON.stringify(response.headers));
        console.log('Response:', body);
        res.send(body);
}

) }

)}

1 个解决方案

#1


0  

What you generally do is first create your token, which goes back to the client. Client now has a token. Generally this is encoded and contains information like user name, id, any special "roles" they might have, expiration time, etc.

您通常做的是首先创建您的令牌,然后返回给客户端。客户现在有一个令牌。通常,这是编码的,包含用户名,ID,可能具有的任何特殊“角色”,到期时间等信息。

You then have that token attached to the authorization header on any subsequent request.

然后,您可以在任何后续请求中将该令牌附加到授权标头。

Based on the syntax your code, I'm assuming you're using express.js. Please correct me if I'm wrong here. Anyhow, it uses a concept known as "middlewares". Essentially you can run other javascript functions prior to sending back the response... You'd want something like this. Know that I didn't actually test this code out so it likely wouldn't work, but hopefully it points you in the right direction:

基于你的代码的语法,我假设你正在使用express.js。如果我错了,请纠正我。无论如何,它使用了一种称为“中间件”的概念。基本上你可以在发回响应之前运行其他javascript函数......你想要这样的东西。知道我实际上没有测试这个代码,所以它可能不会起作用,但希望它能指出你正确的方向:

router.post('/authorize', function(req, res) {
    request({
        method: 'POST',
        url: 'https://secure.snd.payu.com/pl/standard/user/oauth/authorize',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: "xyz"
    }, function(error, response, body) {
        console.log('Status:', response.statusCode);
        console.log('Headers:', JSON.stringify(response.headers));
        console.log('Response:', body);
        res.send(body); //Here I get necessary Bearer key
    });
});


router.post('/paynow', decodeToken, function(req, res) {
    // here you could now access the user information on the user property of the request.  It's assumed that at this point, the token has all been validated
    const user = req.user;
    console.log(user);
    res.send(`Hello, ${user.name}!`);
});

const decodeToken = (req, res, next) => {
/* do something to decode the token.  Review the documentation for whichever JWT library your'e using on how to do this.  It will be something like this.  */
jwt.decode(req.header['Authorization'])
    .then((decodedToken) => {
        req.user = decodedToken;

        // notice this next() function.  this tells express to execute the next function in line on the router endpoint you have.
        next();
    })
    .catch((error) => {
        // error usually something along the lines of an expired token, token doesn't exist, invalid, etc.
        console.log(error);

        // we immediately send a bad response back.  Thus, code would never even get into the main '/paynow' logic.
        res.status(500).end();
    });
});

Note the use of the decodeToken function as a middleware, and how it calls on next(). I encourage you to review express middleware, or whatever library you're using on how to handle situations like this.

注意使用decodeToken函数作为中间件,以及它如何调用next()。我鼓励您查看快速中间件,或者您正在使用的任何库,以了解如何处理这种情况。

Also, on a side note... you're creeping toward something called "Call Back hell" based on your code you posted. While it has nothing to do with your question, I'd encourage you to google "call back hell" to see why it's bad and what you can do to teach yourself to not use it. :) Happy coding!

另外,在旁注中......你正在根据你发布的代码悄悄走向一个叫做“回叫地狱”的东西。虽然它与你的问题无关,但我鼓励你谷歌“回调地狱”,看看它为什么不好以及你可以做些什么来教你自己不使用它。 :)快乐的编码!

#1


0  

What you generally do is first create your token, which goes back to the client. Client now has a token. Generally this is encoded and contains information like user name, id, any special "roles" they might have, expiration time, etc.

您通常做的是首先创建您的令牌,然后返回给客户端。客户现在有一个令牌。通常,这是编码的,包含用户名,ID,可能具有的任何特殊“角色”,到期时间等信息。

You then have that token attached to the authorization header on any subsequent request.

然后,您可以在任何后续请求中将该令牌附加到授权标头。

Based on the syntax your code, I'm assuming you're using express.js. Please correct me if I'm wrong here. Anyhow, it uses a concept known as "middlewares". Essentially you can run other javascript functions prior to sending back the response... You'd want something like this. Know that I didn't actually test this code out so it likely wouldn't work, but hopefully it points you in the right direction:

基于你的代码的语法,我假设你正在使用express.js。如果我错了,请纠正我。无论如何,它使用了一种称为“中间件”的概念。基本上你可以在发回响应之前运行其他javascript函数......你想要这样的东西。知道我实际上没有测试这个代码,所以它可能不会起作用,但希望它能指出你正确的方向:

router.post('/authorize', function(req, res) {
    request({
        method: 'POST',
        url: 'https://secure.snd.payu.com/pl/standard/user/oauth/authorize',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: "xyz"
    }, function(error, response, body) {
        console.log('Status:', response.statusCode);
        console.log('Headers:', JSON.stringify(response.headers));
        console.log('Response:', body);
        res.send(body); //Here I get necessary Bearer key
    });
});


router.post('/paynow', decodeToken, function(req, res) {
    // here you could now access the user information on the user property of the request.  It's assumed that at this point, the token has all been validated
    const user = req.user;
    console.log(user);
    res.send(`Hello, ${user.name}!`);
});

const decodeToken = (req, res, next) => {
/* do something to decode the token.  Review the documentation for whichever JWT library your'e using on how to do this.  It will be something like this.  */
jwt.decode(req.header['Authorization'])
    .then((decodedToken) => {
        req.user = decodedToken;

        // notice this next() function.  this tells express to execute the next function in line on the router endpoint you have.
        next();
    })
    .catch((error) => {
        // error usually something along the lines of an expired token, token doesn't exist, invalid, etc.
        console.log(error);

        // we immediately send a bad response back.  Thus, code would never even get into the main '/paynow' logic.
        res.status(500).end();
    });
});

Note the use of the decodeToken function as a middleware, and how it calls on next(). I encourage you to review express middleware, or whatever library you're using on how to handle situations like this.

注意使用decodeToken函数作为中间件,以及它如何调用next()。我鼓励您查看快速中间件,或者您正在使用的任何库,以了解如何处理这种情况。

Also, on a side note... you're creeping toward something called "Call Back hell" based on your code you posted. While it has nothing to do with your question, I'd encourage you to google "call back hell" to see why it's bad and what you can do to teach yourself to not use it. :) Happy coding!

另外,在旁注中......你正在根据你发布的代码悄悄走向一个叫做“回叫地狱”的东西。虽然它与你的问题无关,但我鼓励你谷歌“回调地狱”,看看它为什么不好以及你可以做些什么来教你自己不使用它。 :)快乐的编码!