在请求前脚本中向Postman中的每个请求添加标头

Nav*_*ina 4 postman

我想使用此预请求脚本自动将标头添加到整个集合中的每个请求:

pm.request.headers.add({
    'key': "myvar",
    'value': pm.environment.get("myvar")    
});
Run Code Online (Sandbox Code Playgroud)

myvar是环境变量。

不幸的是,它不起作用。我错过了什么?

dsi*_*ari 18

对于那些在 postman ~ 7.10.0 上尝试的人,您可以在预请求脚本中以编程方式将标头添加到请求或集合中(进入集合将为集合内的所有请求添加标头)。

pm.request.headers.add({ 
    // These keys appears when you set a header by hand. Just for fun they are here
    disabled: false,
    description:{
        content: "DescriptionTest",
        type: "text/plain"
    },
    // Your header, effectively
    key: 'KeyTest', 
    name: 'NameTest', 
    // If you set a variable you can access it
    // HeaderTest here has value="ValueHeaderTest"
    value: pm.collectionVariables.get("HeaderTest")
});
Run Code Online (Sandbox Code Playgroud)

代码片段生成器不会显示添加的标题:

GET /get_info.php HTTP/1.1
Host: 192.168.15.25:8001
Content-type: application/json
User-Agent: PostmanRuntime/7.19.0
Accept: */*
Host: 192.168.15.25:8001
Accept-Encoding: gzip, deflate
Connection: keep-alive
Run Code Online (Sandbox Code Playgroud)

但是邮递员控制台将:

GET /get_info.php HTTP/1.1
Content-type: application/json
KeyTest: ValueHeaderTest
User-Agent: PostmanRuntime/7.19.0
Accept: */*
Host: 192.168.15.25:8001
Accept-Encoding: gzip, deflate
Connection: keep-alive
Run Code Online (Sandbox Code Playgroud)


ish*_*egg 15

Postman v7.0.9 开始,现在可以通过在集合上添加预请求脚本来实现。

为此,请转到您的收藏集,右键单击它,选择编辑,然后转到Pre-request Scripts选项卡,您可以在其中添加代码段,即:

pm.request.headers.add({
  key: 'X-HEADER-TEST',
  value: '1'
});
Run Code Online (Sandbox Code Playgroud)


J.L*_*Lin 9

看起来pm.request.headers.add()当前未更新正在发送的请求。它被标记为功能请求:https : //github.com/postmanlabs/postman-app-support/issues/4631

您可能已经知道,可以创建预设标头(从“预设”下拉列表中),以使标头设置更加容易。在“设置”下有几个选项可以包含特定的标题。但是,这些建议不会像您所询问的那样自动将标头添加到整个集合中的每个请求中。

更新: Postman在Postman App(v7.0.9)中添加了对此的支持


Abh*_*rma 6

这当然有效。松开键和值上的引号

pm.request.headers.add({
    key: "myvar",
    value: pm.environment.get("myvar")    
});
Run Code Online (Sandbox Code Playgroud)


Dra*_*lut 5

这是从这里复制的,但对我有用

https://gist.github.com/madebysid/b57985b0649d3407a7aa9de1bd327990

pm.sendRequest({
    url: "https://mydomain/ers/config/endpoint",
    method: 'GET',
    header: {
        'content-type': 'application/json',
        'accept': 'application/json',
        //'x-site-code': pm.environment.get("x-site-code")
        'X-CSRF-TOKEN': 'fetch'
    },
    body: {
        mode: 'raw'//,
        raw: JSON.stringify({ email: pm.environment.get("email"), password: pm.environment.get("password") })
    }
}, function (err, res) {

    pm.environment.set("X-CSRF-TOKEN", "Bearer " + res.json().token);
});
Run Code Online (Sandbox Code Playgroud)


pri*_*yGK 5

只需这样添加即可:

pm.request.headers.add("x-api-key: value")
Run Code Online (Sandbox Code Playgroud)

可以使用环境变量:

pm.request.headers.add(`x-api-key: ${pm.environment.get("x-api-key")}`)
Run Code Online (Sandbox Code Playgroud)