【发布时间】:2022-02-14 04:41:20
【问题描述】:
我在 heroku 上有我的 index.html 和必要的 .js 文件。一切正常。现在,我不想将我的用户发送到“myappname.herokuapp.com”,所以我打算使用我自己的网站来存储 .html 文件,但是当用户在我的 HTML 表单上点击“提交”时,我想要执行 Herok NodeJS 代码。
这是 html 的样子
<script>
const form = document.querySelector("form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
try {
displayStatus("processing...");
const request = new Request("/file-upload", {
method: "POST",
body: new FormData(form),
});
const res = await fetch(request);
const resJson = await res.json();
displayResult(resJson.result);
} catch (err) {
displayStatus("an unexpected error");
console.error(err);
}
});
function displayResult(result) {
const content = `Your ID: ${result.id}`;
displayStatus(content);
}
function displayStatus(msg) {
result.textContent = msg;
}
</script>
当实际的 NodeJS 逻辑在“myappname.herokuapp.com”上运行时,如何从位于“mywebsite.com/index.html”上的 HTML 中调用此“/file-upload”
我尝试将“/file-upload”替换为“myappname.herokuapp.com/file-upload”,但它不起作用。
同样,目标是使用我在 Heroku 上的内容,但不让用户访问“myappname.herokuapp.com”,而是应该访问“mywebsite.com/index.html”
谢谢
【问题讨论】:
-
你为什么不把域名连接到heroku服务器呢?除此之外,您必须向 heroku 服务器(来自 mywebsite.com)发出 get 请求,然后才能提供该 index.html 文件
-
是的,但我已经完全建立了“mywebsite.com”。如果我的简单 Heroku 应用程序将替换我的整个现有网站,那么连接它没有多大意义。
-
当用户在 index.html 上点击提交时,向 heroku 服务器发送一个 api 请求以对数据执行您想要的操作,然后将其返回。但是,您似乎在脚本标签中有该逻辑,所以您希望它在前端运行?那么您可能需要将用户重定向到 heroku 应用程序。我认为我没有完全理解您在这里的要求
-
"/file-upload" 是我从前端向 Heroku 发出的 POST 请求(我有一个处理此请求的 index.js)。因为我当前的 Heroku 应用程序在同一位置有 index.html 和 index.js,所以“/file-upload”可以正常工作。当我将 index.html 移动到不同的主机(不是 Heroku)时,“/file-upload”不起作用。
-
你能发布服务器代码吗?如果你移动 index.html,你也必须从你移动它的地方去获取它。