postman使用教程18-如何取出返回 cookie 中的 sessionId 值

前言

接口返回的token一般是通过json格式返回过来的,可以通过 pm.response.json() 解析后直接取值。
sessionId 这种参数一般会放在返回的cookies里面,那么postman 中接口返回 cookies 中的值如何取出呢?

接口案例

当我们请求登录接口,输入账号和密码,请求报文如下

POST http://localhost:8000/api/v1/login HTTP/1.1
User-Agent: Fiddler
Host: localhost:8000
Content-Length: 40
Content-Type: application/json

{"username":"test2","password":"123456"}

接口返回的token在返回body中可以获取到

HTTP/1.1 200 OK
Date: Thu, 21 Oct 2021 13:55:01 GMT
Server: WSGIServer/0.2 CPython/3.6.6
Content-Type: application/json
Vary: Accept, Cookie
Allow: POST, OPTIONS
X-Frame-Options: SAMEORIGIN
Content-Length: 108
Set-Cookie: sessionId=c6193128779902ea8a34847e883ecc50a5bdc693; Path=/

{"code":0,"msg":"login success!","data":{"user":"test2","token":"c6193128779902ea8a34847e883ecc50a5bdc693"}}

取出 body 中的 token

先看下返回json格式的时候,token是如何取值的

在Tests 中编写以下代码,取出 token在 console 中输出

// reponse解析json
jsonData = pm.response.json();
// console
console.log(jsonData.data.token);

console 中输出结果

取出返回cookie中的sessionId

返回的headers 的Set-Cookie 中有个sessionId=e41befda58374a546f5f4290e75eb2ae11640bb5,我们主要是想获取sessionId对应的值

在Tests 中编写以下代码,注意这里是 postman.getResponseCookie(),不是pm.getResponseCookie(),这2个是有区别的。

// 获取返回的cookies
sessionId = postman.getResponseCookie("sessionId").value
console.log(sessionId);

console 中输出结果

取出返回头部 headers 中的值

如果取出的值,仅仅是返回头部的,如下:Server: WSGIServer/0.2 CPython/3.6.6

在Tests 中编写以下代码

// 获取返回的cookies
server = postman.getResponseHeader("Server")
console.log(server);


console 中输出结果

原文地址:https://www.cnblogs.com/yoyoketang/p/15435525.html