我有一组针对相同API的JSON POST请求.API与请求 struct 是相同的(相同的URL),只有几个值在相同的JSON主体中发生变化,这将改变业务场景.我想要实现的是将标准请求存储在一个变量中,并只更改预请求脚本中受影响的值. 这必须是动态的和可重复使用的.

我确实在Collection-Request脚本中配置了以下内容(我会让它变得简单)

const StandardCreateReq = {
  "FullName" : "{{FUllName}}",
  "ApplicantWebGuid": `${pm.environment.get('APPWEBGUID')}`,
  "Address": "Main Street"
};
pm.environment.set("CreateRequest" , JSON.stringify(StandardCreateReq));

在请求正文中,我并没有编写完整的JSON正文,而是将其配置如下:

♫创建请求♫

到目前为止,它工作正常,我能够正确发送请求. 我想要做的是,在单个请求的预请求脚本中(注意,不在集合的预请求脚本中)能够更改一些值,例如,具有特定值的地址,或者像EXISTING_APPWEBGUID这样的环境变量,而不是我正在使用的APPWEBGUID.

I'd need to do this for several requests and I don't want to rewrite the json body everytime and just changing values, I want only within the specific request and as a pre-request action, to be able to change only one or two values. The idea and the difficulty it would be to retrieve the string ♫创建请求♫ and change values in it, I tried with JSON.parse but I'm not able to make it work :-( A possible result would be to send request like following Request 1

{
  "FullName" : "John Doe",
  "ApplicantWebGuid": "12345",
  "Address": "Main Street"
}

请求2

{
  "FullName" : "Jack Brown",
  "ApplicantWebGuid": "67890",
  "Address": "Main Street"
}

希望你明白我的意思,你能帮我

推荐答案

postman Run Collection可以通过更改正文内容来使用相同的URL进行重复API调用.

Mocking server

另存为server.js

const express = require('express');
const fs = require('fs');
const multer = require('multer')
const cors = require('cors');

const app = express();

// for 表格-日期
const forms = multer();
app.use(forms.array()); 

app.use(cors());
const PORT = 3000;

// Function to generate random 5-digit number
function generateRandomNumber() {
    return Math.floor(10000 + Math.random() * 90000);
}

app.post('/v1/address', (req, res) => {
    fs.readFile('address-data.json', 'utf8', (err, data) => {
        if (err) {
            console.error('Error reading file:', err);
            res.status(500).send('Internal Server Error');
            return;
        }

        try {
            const jsonData = JSON.parse(data);
            res.json(jsonData);
        } catch (error) {
            console.error('Error parsing JSON:', error);
            res.status(500).send('Internal Server Error');
        }
    });
});


app.post('/v1/request', (req, res) => {
    const { FullName, ApplicantWebGuid, Address } = req.body;
    // Form data print
    console.log(`FullName: ${FullName}`);
    console.log(`ApplicantWebGuid: ${ApplicantWebGuid}`);
    console.log(`Address: ${Address}`);
    res.json({
        Application: 'virtual Application',
        name: FullName,
        id: ApplicantWebGuid,
        address: Address,
        result: 'Approved'
    });
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Address data

模拟服务器将使用此地址 另存为'address-data.json'

{
    "data": [
        {
            "FullName" : "John Doe",
            "ApplicantWebGuid": "12345",
            "Address": "Main Street"
        },
        {
            "FullName" : "Jack Brown",
            "ApplicantWebGuid": "67890",
            "Address": "Main Street"
        }
    ]
}

安装服务器依赖项

npm install express multer cors

运行服务器

node server.js

enter image description here

API Test

获取地址 URL

http://localhost:3000/v1/address

enter image description here

申请申请 URL

POST http://localhost:3000/v1/request

表格-日期

FullName : John Doe
ApplicantWebGuid: 12345
Address: Main Street

enter image description here

Loop Test

节省1-1-demo.postman_collection.json

{
    "info": {
        "_postman_id": "b0791408-a367-47c1-a96c-3b305a634c10",
        "name": "1-1-demo",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
        "_exporter_id": "1826150"
    },
    "item": [
        {
            "name": "Get Address",
            "event": [
                {
                    "listen": "test",
                    "script": {
                        "exec": [
                            "const jsonData = pm.response.json();\r",
                            "const FullNames = jsonData.data.map(item => item.FullName);\r",
                            "const ApplicantWebGuids = jsonData.data.map(item => item.ApplicantWebGuid);\r",
                            "const Addresss = jsonData.data.map(item => item.Address);\r",
                            "pm.environment.set('FullNames', JSON.stringify(FullNames));\r",
                            "pm.environment.set('ApplicantWebGuids', JSON.stringify(ApplicantWebGuids));\r",
                            "pm.environment.set('Addresss', JSON.stringify(Addresss));\r",
                            "console.log(\"FullNames data: \" + pm.environment.get(\"FullNames\"));\r",
                            "console.log(\"ApplicantWebGuids data: \" + pm.environment.get(\"ApplicantWebGuids\"));\r",
                            "console.log(\"Addresss data: \" + pm.environment.get(\"Addresss\"));"
                        ],
                        "type": "text/javascript"
                    }
                }
            ],
            "request": {
                "method": "POST",
                "header": [],
                "url": {
                    "raw": "http://localhost:3000/v1/address",
                    "protocol": "http",
                    "host": [
                        "localhost"
                    ],
                    "port": "3000",
                    "path": [
                        "v1",
                        "address"
                    ]
                }
            },
            "response": []
        },
        {
            "name": "Request A",
            "event": [
                {
                    "listen": "test",
                    "script": {
                        "exec": [
                            "const jsonData = pm.response.json();\r",
                            "\r",
                            "console.log(\"FullName: \" + pm.environment.get(\"FullName\"));\r",
                            "\r",
                            "let FullNames = JSON.parse(pm.environment.get(\"FullNames\"));\r",
                            "if (FullNames.length > 0){\r",
                            "    postman.setNextRequest(\"Request A\");\r",
                            "}\r",
                            "\r",
                            "const FullName = jsonData.name;\r",
                            "\r",
                            "pm.test('FullName suhold be applicant equal', function () {\r",
                            "    pm.expect(FullName).to.eql(pm.environment.get(\"FullName\"));\r",
                            "});"
                        ],
                        "type": "text/javascript"
                    }
                },
                {
                    "listen": "prerequest",
                    "script": {
                        "exec": [
                            "let FullNames = JSON.parse(pm.environment.get(\"FullNames\"));\r",
                            "console.log(FullNames);\r",
                            "pm.environment.set(\"FullName\", FullNames.shift())\r",
                            "pm.environment.set(\"FullNames\", JSON.stringify(FullNames));\r",
                            "\r",
                            "let ApplicantWebGuids = JSON.parse(pm.environment.get(\"ApplicantWebGuids\"));\r",
                            "console.log(ApplicantWebGuids);\r",
                            "pm.environment.set(\"ApplicantWebGuid\", ApplicantWebGuids.shift())\r",
                            "pm.environment.set(\"ApplicantWebGuids\", JSON.stringify(ApplicantWebGuids));\r",
                            "\r",
                            "let Addresss = JSON.parse(pm.environment.get(\"Addresss\"));\r",
                            "console.log(Addresss);\r",
                            "pm.environment.set(\"Address\", Addresss.shift())\r",
                            "pm.environment.set(\"Addresss\", JSON.stringify(Addresss));"
                        ],
                        "type": "text/javascript"
                    }
                }
            ],
            "request": {
                "method": "POST",
                "header": [],
                "body": {
                    "mode": "formdata",
                    "formdata": [
                        {
                            "key": "FullName",
                            "value": "{{FullName}}",
                            "type": "text"
                        },
                        {
                            "key": "ApplicantWebGuid",
                            "value": "{{ApplicantWebGuid}}",
                            "type": "text"
                        },
                        {
                            "key": "Address",
                            "value": "{{Address}}",
                            "type": "text"
                        }
                    ]
                },
                "url": {
                    "raw": "http://localhost:3000/v1/request",
                    "protocol": "http",
                    "host": [
                        "localhost"
                    ],
                    "port": "3000",
                    "path": [
                        "v1",
                        "request"
                    ]
                }
            },
            "response": []
        }
    ]
}

Import this collection into Postman

enter image description here

enter image description here

enter image description here

Run collection

enter image description here

enter image description here

Result

具有不同两个人名的相同URL API调用 和控制台屏幕上的测试登录结果.

http://localhost:3000/v1/request

enter image description here

Keys

Pre-request Scripts选项卡获取人员信息

let FullNames = JSON.parse(pm.environment.get("FullNames"));
console.log(FullNames);
pm.environment.set("FullName", FullNames.shift())
pm.environment.set("FullNames", JSON.stringify(FullNames));

let ApplicantWebGuids = JSON.parse(pm.environment.get("ApplicantWebGuids"));
console.log(ApplicantWebGuids);
pm.environment.set("ApplicantWebGuid", ApplicantWebGuids.shift())
pm.environment.set("ApplicantWebGuids", JSON.stringify(ApplicantWebGuids));

let Addresss = JSON.parse(pm.environment.get("Addresss"));
console.log(Addresss);
pm.environment.set("Address", Addresss.shift())
pm.environment.set("Addresss", JSON.stringify(Addresss));

enter image description here

Body picked up one of people enter image description here

Tests选项卡判断匹配的用户是否正确

const jsonData = pm.response.json();

console.log("FullName: " + pm.environment.get("FullName"));

let FullNames = JSON.parse(pm.environment.get("FullNames"));
if (FullNames.length > 0){
    postman.setNextRequest("Request A");
}

const FullName = jsonData.name;

pm.test('FullName suhold be applicant equal', function () {
    pm.expect(FullName).to.eql(pm.environment.get("FullName"));
});

enter image description here

Javascript相关问答推荐

模块与独立组件

useNavigation更改URL,但不呈现或显示组件

在nextjs服务器端api调用中传递认证凭证

当试图显示小部件时,使用者会出现JavaScript错误.

我的服务工作器没有连接到我的Chrome扩展中的内容脚本.我该怎么解决这个问题?

阿波罗返回的数据错误,但在网络判断器中是正确的

我在我的Java代码中遇到了问题,代码的一部分看不到先前定义的对象

变量的值在Reaction组件中的Try-Catch语句之外丢失

如何在ASP.NET项目中使用Google Chart API JavaScript将二次轴线值格式化为百分比

以Angular 实现ng-Circle-Progress时出错:模块没有导出的成员

从页面到应用程序(NextJS):REST.STATUS不是一个函数

MongoDB受困于太多的数据

使用父标签中的Find函数查找元素

在表单集中保存更改时删除';禁用';

有没有办法通过使用不同数组中的值进行排序

Chart.js Hover线条在鼠标离开时不会消失

如何向内部有文本输入字段的HTML表添加行?

使用静态函数保存 node 前的钩子

JSON Web令牌(JWT)错误:RSA密钥对的签名无效

JavaScript structuredClone在Chrome/Edge中获得了非法调用,但在NodeJS中没有