【问题标题】:How to change body of API POST request with script?如何使用脚本更改 API POST 请求的正文?
【发布时间】:2017-11-07 13:50:50
【问题描述】:

我一个小时前刚开始学习 API,并希望在我写的一个小帖子中得到输入。我对所有这些工作原理的理解是非常错误的。最重要的是,我想知道如何将变量从脚本传递到 API 请求。

身体:

{
   "bot_id" : "abc123",
   "text" : words
}

以及javascript中的预请求脚本:

var num = Math.floor((Math.random() * 3) + 1);

switch(num)
{
    case 1:
        words = "Hello world!";
        break;
    case 2:
        words = "Greetings Earthlings.";
        break;
    case 3:
        words = "Goodbye cruel world!";
        break;
}

这是我在失败时得到的响应(400 Bad Request):

{
    "meta": {
        "code": 400,
        "errors": [
            "Invalid bot_id"
        ]
    },
    "response": null
}

【问题讨论】:

  • 这有什么问题?你有哪些教程没有回答的问题?这里的实际问题是什么?
  • 这段代码的目的不明确……但没有错。
  • 您的 api 使用什么服务器端代码?
  • "text" : "hello" 请求成功,"text" : words 请求失败。似乎没有读取变量。最大的问题是,如何将变量从脚本传递到请求正文?我找不到涵盖该内容的教程。
  • 它是如何失败的?我们看不到你的机器。

标签: javascript api postman


【解决方案1】:

回应

响应 "errors": ["Invalid bot_id"] 告诉您bot_id (abc123) 是错误的。后端可能有一些验证?

如何将值传递给请求

在预请求脚本中,您可以访问postman 对象。该对象具有setGlobalVariablegetGlobalVariablesetEnvironmentVariablegetEnvironmentVariable 方法。

现在使用此方法,您可以读取/写入变量。在您的情况下,您想使用postman.setGlobalVariable('words', words)。在正文中,您可以使用花括号 {{variable}}

来使用变量

代码

预请求脚本

var num = Math.floor((Math.random() * 3) + 1);
var words = "";

switch(num) {
    case 1:
        words = "Hello world!";
        break;
    case 2:
        words = "Greetings Earthlings.";
        break;
    case 3:
        words = "Goodbye cruel world!";
        break;
}

postman.setGlobalVariable('words', words)

身体

{
    "bot_id" : "abc123",
    "text" : "{{words}}"
}

【讨论】:

  • 就是这样; bot_id 仅在不是“文本”时无效:“一些硬编码值”。我尝试了您使用 set 变量和花括号进行的代码编辑。它得到了与以前相同的响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-09
  • 1970-01-01
相关资源
最近更新 更多