Alomerry Wu @ alomerry.com

api 工具手册

Mar 5, 2021 · 1min · 199 · · updated at 8 months ago

postman

Environments

Environments

Pre-request Script[1]

pre-request

const lastResponseStatus = pm.environment.get('lastResponseStatus')

if (lastResponseStatus != 200) {
  const accountId = pm.environment.get('accountId')
  const data = {
    account: '',
    password: '',
    accountId
  }
  const openapi_business_domain = pm.environment.get('openapi-business')

  const loginRequest = {
    url: `https://${openapi_business_domain}/v2/login`,
    method: 'POST',
    header: 'Content-Type:application/json',
    body: {
      mode: 'raw',
      raw: JSON.stringify(data)
    }
  }
  pm.sendRequest(loginRequest, (err, res) => {
    if (err) {
      console.log(err)
    }
    else {
      const jsonData = res.json()
      pm.environment.set('X-Access-Token', jsonData.accessToken)
    }
  })
}

Tests

pm.environment.set('lastResponseStatus', pm.response.code)

请求 API

pre-request

Case

使用 Environment、Pre-request Script 注入请求参数

测试 API 时需要 mock 一个随机字符串

pre-request script 代码[2]

let randomId = (new Date()).toISOString() + Math.random().toString(36).slice(-8);
pm.environment.set('randomId', randomId);

Reference

  1. Postman JavaScript reference ↩︎

  2. 原生 JAVAScript 生成简单随机字符串 ↩︎

 
 comment..
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v3.0.1
Theme by antfu
2018 - Present © Alomerry Wu