创建包含javascript POST操作的动态网页

时间:2019-01-21 20:54:55

标签: javascript python html rest fetch

我正在构建包括服务条款电子邮件的自动化工作流程(vRA)。如果客户需要共享驱动器,则他们必须接受TOS,然后自动创建驱动器。

工作流的症结是vRO中的自定义事件,该事件等待POST请求。这适用于POSTMAN,我一直遇到的问题是执行POST的网页链接。

我正在尝试创建一个仅将POST传递到此自定义事件的网页,该网页将嵌入Auth令牌,该令牌将在10分钟后失效。

在完成了我认为是困难的工作之后,我一次又一次地尝试使该方法开始工作,但结果却以失败告终。

def createwebpage(customevent, token):
   #Create javascript based webpage
   customevent = unicode(customevent, "utf-8")
   url = "https://automationserver/vco/api/customevent/" + customevent
   authtoken = "'Bearer ,Bearer " + token + "',"
   webpage = ("<html>\n" +
            "<head>\n" +
            "<script type=\"text/javascript\">\n" +
            "console.log(\"This is a test...\");\n" +
            "async function userAction() {\n" +
              "const URL = '" + url + "';\n"
              "fetchInit = {\n" +
                "method: 'POST',\n" +
                "mode: 'no-cors',\n" +
                "credentials: 'include',\n" +
                "body: '{\"executionId\": \"\",\"parameters\": [],\"profilerOptions\": {\"enabled\": true}',\n" +
                "headers: {\n" +
                    "'Content-Type': 'application/json',\n" +
                    "'Authorization': " + authtoken + "\n" +
                    "'cache-control': 'no-cache',\n" +
                    "'Accept': 'application/json'\n" +
                  "}\n" +
                "};\n" +
              "try {\n" +
                  "const fetchResult = fetch(\n" +
                  "new Request(URL, fetchInit));\n" +
                  "console.log(\"Completed request\");\n" +
                  "document.write(\"<b>Drive has been created...</b>\");\n" +
                "} catch (e) {\n" +
                "  throw Error(e);\n" +
                "}\n" +
              "};\n" +
          "</script>\n" +
        "</head>\n" +
          "<body>\n" +
              "<b>The shared drive located at CO - CO Test CANNOT be used to store - HIPPA / PCI information!!</b>\n" +
              "<br>\n" +
              "<b>By clicking Accept below you acknowledge no HIPPA / PCI information will be stored within the contents of files</b>\n" +
              "<br>\n" +
              "<br>\n" +
              "<form>\n" +
                "<button type=\"submit\" onclick=\"userAction()\">Accept</button>\n" +
              "</form>\n" +
            "</div>\n" +
          "</body>\n" +
        "</html>\n")
   #Write to file
   filename = '/tmp/web/' + customevent + ".html"
   with open(filename, 'w') as f:
      f.write(webpage)

此python代码将生成的网页如下。

<html>
<head>
<script type="text/javascript">
console.log("This is a test...");
async function userAction() {
const URL = 'https://automationserver/vco/api/customevent/58a4a5c2-160b-4d3f-bec9-7b7071cd6b0e';
fetchInit = {
method: 'POST',
mode: 'no-cors',
credentials: 'include',
body: '{"executionId": "","parameters": [],"profilerOptions": {"enabled": true}',
headers: {
'Content-Type': 'application/json',
'Authorization': 'token',
'cache-control': 'no-cache',
'Accept': 'application/json'
}
};
try {
const fetchResult = fetch(
new Request(URL, fetchInit));
console.log("Completed request");
document.write("<b>Drive has been created...</b>");
} catch (e) {
  throw Error(e);
}
};
</script>
</head>
<body>
<b>The shared drive located at CO - CO Test CANNOT be used to store - HIPPA / PCI information!!</b>
<br>
<b>By clicking Accept below you acknowledge no HIPPA / PCI information will be stored within the contents of files</b>
<br>
<br>
<form>
<button type="submit" onclick="userAction()">Accept</button>
</form>
</div>
</body>
</html>

请注意,我已经在自动化工作流程中使用了三个系统-我意识到建议是删除无约束条件并提交给代理(为什么我不知道-这似乎很愚蠢),但我想避免创建另一个依赖项。

任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

似乎您不正确地使用了Fetch API。

我用我认为可以正常工作的代码重写了userAction函数。重要的是要注意,fetch仅在发出HTTP请求时遇到错误时才会抛出错误。如果对该请求的响应为400或500,它将处理为成功请求。

仅供参考,此代码可能不适用于任何版本的Internet Explorer。因此,如果您在IE上有用户,则将无法使用。您将需要使用XMLHttpRequest或通过CDN获得第三方依赖项来为您处理网络请求。

function userAction() {
  const URL = 'https://automationserver/vco/api/customevent/58a4a5c2-160b-4d3f-bec9-7b7071cd6b0e';
  fetchInit = {
    method: 'POST',
    mode: 'no-cors',
    credentials: 'include',
    body: '{"executionId": "","parameters": [],"profilerOptions": {"enabled": true}',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'token',
      'cache-control': 'no-cache',
      'Accept': 'application/json',
    },
  };

  return fetch(URL, fetchInit)
    .then((response) => {
      if (response.status === 200) {
        console.log("Completed request");
        document.write("<b>Drive has been created...</b>");
      } else {
        console.log('Non 200 response:');
        console.log(response.status, response.statusText);
      }
    })
    .catch((err) => {
      console.log('Encountered error:');
      console.log(err);
    });
};

答案 1 :(得分:0)

安德鲁·迪布尔(Andrew Dibble)的答案几乎可以解决我的问题,但是将其包含在Firefox(在Chrome中工作)后,我开始出现以下错误。

TypeError: NetworkError javascript fetch

此问题已通过从HTML正文中删除表单来解决。熟悉javascript复杂性的人也许可以解释。

允许POST的最终代码。

<html>
<head>
<script type='text/javascript'>
function postData(url = ``, data = {}) {
  return fetch('https://automationserver/vco/api/customevent/event-code', {
  "method": "POST",
  "mode": "no-cors",
  "cache": "no-cache",
  "credentials": "include", // include, *same-origin, omit
  "headers": {
    "Content-Type": "application/json",
    "Authorization": 'token-here',
    "cache-control": "no-cache",
    "Accept": "application/json",
  },
  "redirect": "follow",
  "referrer": "no-referrer",
  "body": JSON.stringify(data)
})
.then(response => response.json());
}
</script>
</head>
<body>
<b>The shared drive CANNOT be used to store - HIPPA / PCI information!!</b>
<br>
<b>By clicking Accept below you acknowledge no HIPPA / PCI information will be stored within the contents of files</b>
<br>
<br>
<button type="submit" onclick="postData()">Accept</button>
</div>
</body>
</html>