我有一个简单的shell脚本,希望在后台运行并将其分配给Postman全局变量。有任何关于如何在Postman中实现此目标的想法吗?
Postman只能触发HTTP请求,因此我们没有直接执行例如.sh脚本的方法。 但是,您可以运行一个本地服务器(这里使用node js服务器),并编写一个node js脚本来执行shell脚本或其他可执行文件。 现在让我们逐步进行:
我有一个PHP脚本,它提供了令牌。此令牌将在API请求中使用。该脚本看起来像下面这样,并保存为TokenGenerator.php。
<?php
require "vendor/autoload.php";
class TokenGeneration {
public $appID= "50A454F3-EE11-4A4C-B708-965BC7640C08";
public $token = NULL;
public function __construct(){
//echo "\n URL: ".$this->url;
$this->token = $this->generateAppToken();
}
function generateAppToken(){
$message = $this->appID."~REQUEST".time();
//echo "\n message: ".$message;
$cryptor = new \RNCryptor\RNCryptor\Encryptor;
$base64Encrypted = $cryptor->encrypt($message, $this->appID);
//echo "\n token: ". $base64Encrypted;
return $base64Encrypted;
}
}
?>
我们将编写 token.php 程序从 TokenGenerato.php 获取令牌。
<?php
require "TokenGeneration.php";
$tokengen = new TokenGeneration();
echo $tokengen->token;
?>
我们可以通过以下方式运行此php脚本:
php token.php
输出结果:
AwFmHNkA1HdM1VHFadu89nE3xZuKO3pLQ7cHOrCj2x2WZoSt
您可以使用child_process模块在Node.js中执行shell命令。 child_process教程
在 token.js 中创建以下代码的Node.js脚本:
const http = require('http'), { exec } = require('child_process');
http.createServer((req, res) => {
// Give the path of your bat or exe file
exec('php token.php', (err, stdout, stderr) => {
console.log({ err, stdout, stderr });
if (err) {
return res.writeHead(500).end(JSON.stringify(err));
}
// Output of the script in stdout
return res.writeHead(200).end(stdout);
});
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
接下来,使用以下命令启动Node服务器。
node token.js
首先,在Postman中创建新的API请求,然后选择Pre-request Script并编写以下代码,在实际API调用发生之前发送http请求并将响应保存在本地变量中。
pm.variables.set("password", "AwErFEinDqiOvXFx2wVgHvt+Rpo0jdoTH0D0QldS");
console.log("password: ", pm.variables.get("password"));
pm.sendRequest('http://127.0.0.1:8000', (err, response) => {
// This will have the output of your batch file
console.log(response.text());
pm.variables.set("token", response.text());
})
最后,准备使用令牌的标头
令牌 = {{token}}
不要使用全局变量,而是使用环境变量。
在Postman中,环境可以导入/导出为简单的JSON文件,这些文件可以轻松地通过外部脚本进行修改。