• postman使用教程19-collection添加Pre-request Scripts 解决登录依赖token


    前言

    postman可以在接口请求Pre-request 添加请求前的操作,很多接口都是依赖于先登录的。于是可以在Pre-request 发送一个登录请求获取token。
    当接口较多的时候,每个接口前面加一次会很麻烦,这种公共操作可以写到collection 集合中添加 Pre-request Scripts

    collection添加Pre-request Scripts

    collection - edit 编辑界面点开 Pre-request Scripts

    添加代码

    const regRequest = {
      url: 'http://localhost:8000/api/v1/login',
      method: 'POST',
      header: 'Content-Type: application/json',  
      body: {
        mode: 'raw', 
        raw: JSON.stringify({ username: 'test', password: '123456' })
      }
    };
    
    // 发送登录请求,获取token
    pm.sendRequest(regRequest, function (err, res) {
      console.log(res.json()['token']);  
      pm.variables.set('token', res.json()['token'])
    
    });
    
    // 更新到请求头部
    pm.request.headers.add({
        key:"Authorization",
        value:"Token {{token}}"
    });
    

    依赖登录的接口

    依赖登录的接口,请求头部不需要再添加Authorization:Token {{token}}

    查看Console 可以看到会先执行登录,自动更新请求头部token值

  • 相关阅读:
    Python包中__init__.py作用
    获取web页面xpath
    Selenium学习(Python)
    C++构造函数的选择
    分布式实时处理系统——C++高性能编程
    构建之法(邹欣)
    分布式实时处理系统——通信基础
    go语言-csp模型-并发通道
    redis.conf 配置说明
    Linux fork()一个进程内核态的变化
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/15502096.html
Copyright © 2020-2023  润新知