Add header to every request in Postman in pre-request script

前端 未结 7 2081
春和景丽
春和景丽 2021-02-05 07:00

I want to automatically add a header to every request in my whole collection using this pre-request script:

pm.request.headers.add({
    \'key\': \"myvar\",
             


        
7条回答
  •  醉话见心
    2021-02-05 07:47

    For those who are trying it on postman ~ 7.10.0, you can add headers programmatically in a pre-request script, into the request or into the collection (into collection will add headers to all requests inside collection).

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

    The code snippet generator will not show the added header:

    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
    

    But the Postman Console will:

    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
    

提交回复
热议问题