How to store and reuse cookies in Postman?

后端 未结 4 1102
感情败类
感情败类 2021-02-20 10:00

I\'m using Postman to test and play with an API.

For the login url, the API requires sending a POST request with username and password as fiel

相关标签:
4条回答
  • 2021-02-20 10:18

    Store the cookie value you want to use in a global variable.In Tests tab of login request, write

    postman.setGlobalVariable('key', postman.getResponseCookie("cookieName").value);
    

    Pass along with the value in the Headers tab as a cookie in get user request:

    Cookie | cookieName={{key}}
    
    0 讨论(0)
  • 2021-02-20 10:23

    I tried using Ashutosh's answer but got an error. I'm guessing this is because Postman's scripting API changed?

    At any rate, the following worked for me:

    1. In the Tests tab of the request that will return cookies you want to save, write
    pm.globals.set('<your key>', pm.cookies.get('<cookie name>'));
    
    1. Then, as described in Ashutosh's answer, add the cookie to the headers by setting the key as cookie and corresponding value as <your cookie name>={{<global variable name>}};.

    I found documentation for this at the Postman sandbox API reference.

    0 讨论(0)
  • 2021-02-20 10:29

    It seems there are two Interceptor plugin in google chrome. make sure install the correct one.

    0 讨论(0)
  • 2021-02-20 10:35

    (Updated Dec 18 2020, using the native Postman app without the interceptor) The traditional way of reading the cookie does not work for me pm.cookies.get('<cookie name>') . Here is a workaround that automatically attaches auth cookie to all requests within a collection:

    // The test scripts below run after the api /login returns the response
    
    const authCookie = pm.response.headers.idx(3).value
    /* 
    pm.response.headers.idx(3) is equal to:
    {key: "Set-Cookie", value: "xs=eyJhb; Max-Age=3600; Path=/; Expires=Fri, 18 Dec 2020 04:40:34 GMT; HttpOnly; Secure; SameSite=None"} 
    */
    
    const token = authCookie.substring(3, authCookie.indexOf(';'))
    pm.collectionVariables.set('xs_value', token);
    

    Then add this pre-request scripts to the entire collection:

    // Scripts below runs before any request within a collection is sent
    
    const token = pm.collectionVariables.get('xs_value')
    pm.request.headers.upsert({ key: 'Cookie', value: `xs=${token}` })
    

    Enjoy!

    More info on how to attach headers to requests

    0 讨论(0)
提交回复
热议问题