Javascript 如何使用脚本更改API POST请求的主体?
我一个小时前才开始学习API,想在我写的一篇小帖子上发表意见。我对这一切如何运作的理解是非常错误的。最重要的是,我想知道如何将变量从脚本传递到API请求 该机构:Javascript 如何使用脚本更改API POST请求的主体?,javascript,api,postman,Javascript,Api,Postman,我一个小时前才开始学习API,想在我写的一篇小帖子上发表意见。我对这一切如何运作的理解是非常错误的。最重要的是,我想知道如何将变量从脚本传递到API请求 该机构: { "bot_id" : "abc123", "text" : words } 以及javascript中的预请求脚本: var num = Math.floor((Math.random() * 3) + 1); switch(num) { case 1: words = "Hello wor
{
"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个错误请求失败时得到的响应:
{
"meta": {
"code": 400,
"errors": [
"Invalid bot_id"
]
},
"response": null
}
反应
响应错误:[无效的机器人id]告诉您机器人id abc123错误。后端可能有一些验证
如何将值传递给请求
在预请求脚本中,您可以访问postman对象。此对象具有方法setGlobalVariable、getGlobalVariable、setEnvironmentVariable和getEnvironmentVariable
现在,使用这种方法,您可以读取/写入变量。在您的情况下,您需要使用postman.setGlobalVariable'words',words。在主体内部,可以使用大括号{{variable}使用变量
密码
请求前脚本
身体
怎么了?你有哪些问题是教程没有回答的?这里的实际问题是什么?这个代码的目的不清楚。。。但是它没有错。您的api使用什么服务器端代码?当text:hello时请求成功,但当text:words时请求失败。似乎没有读取变量。最大的问题是,如何将变量从脚本传递到请求体?我还没有找到一个教程来涵盖这一点。它怎么会失败呢?我们看不到你的机器,就是这样;bot_id仅在非文本时无效:某些硬编码值。我尝试了使用set变量和花括号进行的代码编辑。它得到了和以前一样的反应。
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}}"
}