How to store and reuse cookies in Postman?

后端 未结 4 1130
感情败类
感情败类 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: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('') . 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

提交回复
热议问题