Javascript 在集合中的整个请求中将 Postman 标头值保存到变量中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42372488/
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 01:06:18  来源:igfitidea点击:

Saving a Postman header value into a variable throughout requests in a collection

javascriptautomated-testspostman

提问by jmcode

Good afternoon Stackers,

下午好堆垛机,

I am trying to automate my test suite in Postman so that I don't have to manually go into each request and change that header value to what I initially put in the first request.

我正在尝试在 Postman 中自动化我的测试套件,这样我就不必手动进入每个请求并将该标头值更改为我最初放在第一个请求中的值。

My test suite currently looks like:

我的测试套件目前看起来像:

First Request:

第一个请求:

var headerValue = postman.setGlobalVariable('Number', headerValue);
console.log("Number is: " + headerValue);

Second Request Header:

第二个请求头:

Number - {{headerValue}}

I would expect headerValue to have the value of 'Number' since I have set it as a global variable but it is coming back as undefined. I'm not sure what I am doing wrong.

我希望 headerValue 具有 'Number' 的值,因为我已将其设置为全局变量,但它以未定义状态返回。我不确定我做错了什么。

回答by Sai Ram Reddy

This is how you can do this

这就是你可以做到的

If Refresh_token is the header value

如果 Refresh_token 是标头值

postman.setGlobalVariable("refresh_token",postman.getResponseHeader("Refresh_token") );

Official Documentation: https://www.getpostman.com/docs/postman/scripts/test_examples

官方文档:https: //www.getpostman.com/docs/postman/scripts/test_examples

回答by Rostyslav Druzhchenko

It seems like @Sai's answer does not workis not recommended anymore, since getResponseHeaderis deprecated now. The updated code is:

似乎不再推荐@Sai的回答不起作用,因为getResponseHeader现在已弃用。更新后的代码是:

pm.test("First request", function() {
    let headerValue = pm.response.headers.get("Number")
    pm.globals.set("Number", headerValue);
});

In the second request go Headerssection, add a new header with Numberas a key and {{Number}}as a value.

在第二个请求 goHeaders部分中,添加一个Number作为键和{{Number}}值的新标头。

回答by Alex Efimov

Simple approach with logging of you header before saving it to variable:

在将标题保存到变量之前记录标题的简单方法:

let authToken = postman.getResponseHeader("Authorization")
console.log("auth header -> ", authToken)
postman.setEnvironmentVariable("auth", authToken)

回答by Always Sunny

No, try this way. For postman, if you want to set environment or global variable just use (key,value ) pattern this way-

不行,试试这个。对于邮递员,如果您想设置环境或全局变量,只需使用 (key,value ) 模式这种方式-

postman.setEnvironmentVariable(key,value) or   
postman.setGlobalVariable(key,value) 

and finally grab them using {{key}}

最后使用 {{key}} 抓取它们

var headerValue = ”your value goes here”;
postman.setGlobalVariable('Number', headerValue);

and use {{Number}} on your sub subsequent request header

并在您的子后续请求标头上使用 {{Number}}