Last active
December 11, 2019 06:33
-
-
Save ytlm/24890ebab0f4a05caf513bdfddcf6a77 to your computer and use it in GitHub Desktop.
Pre-request Script for postman 技巧
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 生成http Date | |
var today = new Date() | |
var apiDate = today.toUTCString() | |
postman.setEnvironmentVariable("api-date", apiDate); | |
// 获取请求method | |
var method = request.method | |
var contentMd5 = "" | |
var contentLength = "" | |
if (method === "POST") { | |
// 获取请求的body | |
var body = request.data | |
// 计算MD5 | |
contentMd5 = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(CryptoJS.MD5(body).toString())) | |
contentLength = body.length | |
postman.setEnvironmentVariable("api-content-md5", contentMd5); | |
} | |
var contentType = request.headers["Content-Type"] | |
// 有时候需要小写需要看版本 | |
// var contentType = request.headers["content-type"] | |
var string_sig = method + "\n" + contentMd5 + "\n" + contentType + "\n" + contentLength + "\n" + apiDate | |
// 计算加密 | |
// pm.environment.get("auth-prefix") | |
// pm.globals.get("pwd") | |
var apiAuth = environment["auth-prefix"] + CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(string_sig, environment["pwd"])) | |
// pm.environment.set("api-auth", apiAuth); | |
// | |
// pm.globals.set("variable_key", "variable_value"); | |
postman.setEnvironmentVariable("api-auth", apiAuth); | |
////////////////////////////////////////////////////// tests | |
var jsonData = JSON.parse(responseBody); | |
tests["Status code is 200"] = responseCode.code === 200; | |
tests["response body code is 0"] = jsonData.code === 0; | |
tests["erros is null"] = jsonData.errors === undefined; | |
////////////// | |
//Base64 Encode | |
var words = CryptoJS.enc.Utf8.parse('Hello CryptoJS'); | |
var base64 = CryptoJS.enc.Base64.stringify(words); | |
//Base64 Decode | |
let parsedWords = CryptoJS.enc.Base64.parse(base64); | |
let parsedString = parsedWords.toString(CryptoJS.enc.Utf8); | |
// MD5 Encode | |
var hash = CryptoJS.MD5(str).toString(); | |
// timestamp | |
var date = new Date(); | |
var time = (date.getTime() / 1000) + 600; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment