CentOS上Postman使用技巧与窍门
Postman提供了三种主流安装方式,适配不同需求:
/etc/yum.repos.d/postman.repo文件(内容为[postman]、baseurl=https://dl.pstmn.io/download/linux、enabled=1、gpgcheck=1、gpgkey=https://dl.pstmn.io/release/key.asc),执行sudo yum install postman即可完成安装。sudo yum install snapd && sudo systemctl enable --now snapd.socket,再执行sudo snap install postman --classic。.tar.gz文件,解压至/opt目录(如sudo tar -xzf Postman-linux-x64-*.tar.gz -C /opt),创建符号链接sudo ln -s /opt/Postman/Postman /usr/bin/postman,即可在终端通过postman命令启动。为方便图形化启动,可创建桌面启动器:执行sudo touch /usr/share/applications/postman.desktop,编辑文件内容为:
[Desktop Entry]
Encoding=UTF-8
Name=Postman
GenericName=API Tools
Comment=Postman
Exec=/usr/bin/postman
Terminal=false
MimeType=text/plain
Icon=/usr/local/postman/app/resources/app/assets/icon.png
Categories=Development;
StartupNotify=true;
保存后,即可在应用菜单中找到Postman图标。
baseUrl=https://api-dev.example.com、apiKey=123456)。在请求URL或Headers中通过{{变量名}}引用(如GET {{baseUrl}}/users)。pm.globals.set("变量名", "值")设置(如在Pre-request Script中),使用时同样用{{变量名}}引用。将相关请求保存为集合(Collection),便于批量管理和分享。点击左侧“New”→“Collection”,输入名称(如“User API”),将单个请求拖入集合中。可通过“Export”功能导出集合为JSON文件,分享给团队成员;或通过“Import”导入他人共享的集合。
pm.environment.set("timestamp", new Date().toISOString()),可在请求Headers中引用{{timestamp}}。// 检查状态码是否为200
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// 检查响应体是否包含“success”
pm.test("Body contains success", function () {
pm.expect(pm.response.text()).to.include("success");
});
// 解析JSON并验证字段值
pm.test("User name is correct", function () {
const jsonData = pm.response.json();
pm.expect(jsonData.name).to.eql("John Doe");
});
```。
Newman是Postman的命令行工具,可将集合导入服务器,实现自动化API测试。安装Newman:npm install -g newman。运行集合:newman run /path/to/collection.json。可添加参数生成HTML报告(--reporters html --reporter-html-export report.html),便于查看测试结果。
通过Postman创建Mock Server,无需依赖真实后端即可模拟API响应。步骤:点击左侧“Mock Server”→“Create Mock Server”,选择集合,设置响应规则(如GET /users返回[{"id":1,"name":"John"}]),获取Mock URL。后续请求该URL即可得到模拟响应,方便前端开发调试。
掌握常用快捷键可大幅减少鼠标操作:
Ctrl+T(Mac)/ Ctrl+N(Windows);Ctrl+Tab(Mac)/ Ctrl+Shift+Tab(Windows);Ctrl+S(Mac)/ Ctrl+Shift+S(Windows);Ctrl+Enter(Mac)/ Ctrl+Alt+Enter(Windows)。{{变量名}}引用。