如何使用 Postman 中的预请求脚本从另一个请求运行一个请求如何使用、脚本、Postman

由网友(倾尽天下)分享简介:我正在尝试在邮递员中一键发送经过身份验证的请求.I'm trying to send an authenticated request with one click in postman.所以,我有一个名为Oauth"的请求和 我正在使用测试将令牌存储在一个局部变量中.So, I have request nam...

我正在尝试在邮递员中一键发送经过身份验证的请求.

I'm trying to send an authenticated request with one click in postman.

所以,我有一个名为Oauth"的请求和 我正在使用测试将令牌存储在一个局部变量中.

So, I have request named "Oauth" and I'm using Tests to store the token in a local variable.

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.access_token);

我现在要做的是为任何其他需要不记名令牌的请求自动运行 Oauth 请求(来自预请求脚本).

What I'm trying to do now is that run the Oauth request automatically (from a pre-request script) for any other requests which needs a bearer token.

有没有办法通过单击邮递员按钮来获取访问令牌并发送经过身份验证的请求?

Is there a way to get an access token and send an authenticated request with one postman button click?

推荐答案

正如 KBusc 所提到的并从这些示例中得到启发,您可以通过设置如下所示的预请求脚本来实现您的目标:

As mentioned by KBusc and inspired from those examples you can achieve your goal by setting a pre-request script like the following:

pm.sendRequest({
    url: pm.environment.get("token_url"),
    method: 'GET',
    header: {
        'Authorization': 'Basic xxxxxxxxxx==',
    }
}, function (err, res) {
    pm.environment.set("access_token", res.json().token);
});

然后您只需将 {{access_token}} 引用为任何其他环境变量.

Then you just reference {{access_token}} as any other environment variable.

阅读全文

相关推荐

最新文章