Javascript 如何使用 Postman 中的预请求脚本运行来自另一个请求的请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39551635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:40:57  来源:igfitidea点击:

How to run one request from another using Pre-request Script in Postman

javascriptpostman

提问by Lasharela

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

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

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

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

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

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.

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

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

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

回答by Hannele

NOTE: There now isa way to do this in a pre-request script, see the other answers. I'll keep this answer for posterity but just so everyone knows :)

注意:现在一种方法可以在预请求脚本中执行此操作,请参阅其他答案。我会为后代保留这个答案,但只是让每个人都知道:)

I don't think there's a way to do this in the pre-request script just yet, but you can get it down to just a few clicks if you use a variable and the Tests tab. There are fuller instructions on the Postman blog, but the gist of it is:

我认为目前还没有在预请求脚本中执行此操作的方法,但是如果您使用变量和测试选项卡,只需单击几下即可。Postman blog 上有更完整的说明,但其要点是:

  1. Set up your authentication request like normal.
  2. In the Tests section of that request, store the result of that request in a variable, possibly something like the following:

    var data = JSON.parse(responseBody);
    postman.setEnvironmentVariable("token", data.token);
    
  3. Run the authentication request -- you should now see that tokenis set for that environment (click on the eye-shaped icon in the top right).

  4. Set up your data request to use {{token}}wherever you had previously been pasting in the bearer token.
  5. Run your data request -- it should now be properly authenticated.
  1. 像往常一样设置您的身份验证请求。
  2. 在该请求的测试部分,将该请求的结果存储在一个变量中,可能类似于以下内容:

    var data = JSON.parse(responseBody);
    postman.setEnvironmentVariable("token", data.token);
    
  3. 运行身份验证请求——您现在应该看到为该token环境设置的(单击右上角的眼形图标)。

  4. 设置您的数据请求,以{{token}}在您之前粘贴到不记名令牌的任何地方使用。
  5. 运行您的数据请求——它现在应该被正确验证。

To refresh the token, all you should need to do is re-run the authentication request.

要刷新令牌,您需要做的就是重新运行身份验证请求。

回答by KBusc

A little late but for others who come across this post, it IS now possible to send another request from the Pre-request Scriptsection. A few examples can be found here : https://gist.github.com/madebysid/b57985b0649d3407a7aa9de1bd327990

有点晚了,但对于遇到此帖子的其他人,现在可以从该Pre-request Script部分发送另一个请求。一些例子可以在这里找到:https: //gist.github.com/madebysid/b57985b0649d3407a7aa9de1bd327990

回答by Gera Zenobi

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

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

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

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

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

回答by Piotr Dawidiuk

You can't send another request from Pre-request Scriptsection, but in fact, it's possible to chain request and run one after another.

您不能从Pre-request Script部分发送另一个请求,但实际上,可以链接请求并一个接一个地运行。

You collect your request into collection and run itwith Collection Runner.

你收集你的要求为收集和运行它Collection Runner

To view request results you can follow other answer.

要查看请求结果,您可以按照其他答案

回答by Michael Ormrod

You can add a pre-request script to the collection which will execute prior to each Postman request. For example, I use the following to return an access token from Apigee

您可以向集合中添加一个预请求脚本,该脚本将在每个 Postman 请求之前执行。例如,我使用以下内容从 Apigee 返回访问令牌

const echoPostRequest = {
  url: client_credentials_url,
  method: 'POST',
  header: 
      'Authorization: Basic *Basic Authentication string*'

};

var getToken = true;

if (!pm.environment.get('token'))

{
    console.log('Token  missing')

}
else 
{

    console.log('Token all good');
}

if (getToken === true) {
    pm.sendRequest(echoPostRequest, function (err, res) {
    console.log(err ? err : res.json());
        if (err === null) {
            console.log('Saving the token');
            console.log(res);
            var responseJson = res.json();
            console.log(responseJson.access_token);
            pm.environment.set('token', responseJson.access_token)


        }
    });
}

回答by surya pratap singh

I have tried multiple solutions, the below solution is related to when you are parsing the response for request 1 and passing any variable into the second request parameter. ( In this Example variable is Lastname. )

我尝试了多种解决方案,以下解决方案与解析请求 1 的响应并将任何变量传递到第二个请求参数时有关。(在此示例中变量是姓氏。)

Note:- data and user are JSON objects.``

注意:- data 和 user 是 JSON 对象。``

postman.clearGlobalVariable("variable_key");
postman.clearEnvironmentVariable("variable_key");
tests["Body matches string"] = responseBody.has("enter the match string ");
 var jsonData = JSON.parse(responseBody);
  var result = jsonData.data;
  var lastName = result.user.lastName;
tests["Body matches lastName "] = responseBody.has(lastName);
tests["print  matches lastName " + lastName ] = lastName;