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

时间:2017-10-13 13:04:59

标签: node.js express request response

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

{{1}}

) }

1 个答案:

答案 0 :(得分:0)

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

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

根据你的代码的语法,我假设你正在使用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();
    });
});

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

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