Nodejs:如何从HTML前端访问JavaScript后端的功能?
这是我的HTML代码index.html
。
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="stuff()">Click</button>
<script>
async function stuff() {
await connectToServer();
}
async function connectToServer() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(this.responseText);
};
xhttp.open('GET', 'C:/Users/myName/myFolder/index.js', true);
xhttp.send();
return;
}
</script>
</body>
</html>
然后,这是我在index.js中的后端代码。
const express = require('express');
const axios = require('axios');
const port = process.env.PORT || 8080;
const app = express();
app.get('/', (req, res) => {
res.sendFile('C:/Users/myName/myFolder/views/index.html');
});
app.listen(port, () => console.log(`Listening on port ${port}`));
我可以在命令行上键入节点index.js
并运行此程序,然后访问http:// localhost:8080/。当我这样做时,HTML页面按预期显示。但是,当我单击该按钮以向服务器端提出get请求时,我会收到一个控制台错误,说不允许加载本地资源:file:/// c:// cy/users/myname/myfolder/index .js
。顺便说一句,我正在使用Google Chrome。
我知道这是安全性的事情,您应该向Web服务器上的文件提出请求(它们以HTTP或HTTPS开头)。我想那时,我的问题是:
如何制作它,以便我的服务器文件index.js
可以将其视为在服务器上,以便我可以从我的前端从后端调用函数?
Here is my HTML code in index.html
.
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="stuff()">Click</button>
<script>
async function stuff() {
await connectToServer();
}
async function connectToServer() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(this.responseText);
};
xhttp.open('GET', 'C:/Users/myName/myFolder/index.js', true);
xhttp.send();
return;
}
</script>
</body>
</html>
Then, here is my backend code in index.js.
const express = require('express');
const axios = require('axios');
const port = process.env.PORT || 8080;
const app = express();
app.get('/', (req, res) => {
res.sendFile('C:/Users/myName/myFolder/views/index.html');
});
app.listen(port, () => console.log(`Listening on port ${port}`));
I can type node index.js
on the command line and run this program and go to http://localhost:8080/ . When I do this, the html page shows up as intended. However, when I click the button in order to make a GET request to the server side, I get a console error saying Not allowed to load local resource: file:///C:/Users/myName/myFolder/index.js
. I'm using Google Chrome by the way.
I know that it is a security thing, and that you are supposed to make requests to files that are on a web server (they begin with http or https). I suppose then, my question is:
How do I make it so that my server file index.js
can be viewed as being on a server so that I can call functions on the backend from my frontend?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须向服务器提供的URL提出HTTP请求。
您的服务器提供的唯一URL是
http:// localhost:8080/
(因为您正在LocalHost上运行HTTP服务器,已将其配置为在端口8080上运行,并且具有app.get。 ('/',...)
提供唯一的路径,如果您要支持其他URL,然后以类似的方式注册它们并写下一个路由来处理它们
。 expressjs.com/en/starter/basic-routing.html“ rel =” nofollow noreferrer“> Express Documentation 可能有用。
您不需要将服务器端代码加载到浏览器中。它的服务器。它的服务器 的代码。
- 在服务器上运行 服务器,然后使用
&lt; script src =“ url/to/js”&gt;&lt;/script&gt;
(而不是ajax)和配置express'静态中间件。You have to make an HTTP request to a URL provided by the server.
The only URL your server provides is
http://localhost:8080/
(because you are running an HTTP server on localhost, have configured it to run on port 8080, and haveapp.get('/', ...)
providing the only path.If you want to support other URLs, then register them in a similar way and write a route to handle them.
The express documentation will probably be useful.
You should not need to load your server-side code into the browser. It's server-side code. It runs on the server. It isn't client-side code. It doesn't run in the browser. The browser does not need access to it.
If you want to load some actual client-side JS from the server, then use
<script src="url/to/js"></script>
(and not Ajax) and configure express' static middleware.让我们通过将后端API流程与前端托管过程分开来改善当前流程。虽然后端可以,但在提供静态HTML文件(尤其是用于本地开发目的)方面并不是一件好事。
照常运行后端,
节点index.js
。但是,一旦此命令变得更加复杂,您可能需要使用 npm脚本做 npm start ))
)
)运行单独的服务器过程以进行前端。查看 parcel ,雪堆,。它可能像
npx parcel index.html
一样容易,但是随着您对工具功能的理解,此命令可能会经常更改。要调用后端,只需在Express应用中添加一个API端点(就像您已经为静态内容提供的那样),然后使用后端进程URL调用它。
通常,您会在
http:// localhost/
上看到您的应用程序,并且应该向http:// localhost:8080/
进行请求。如果出于某种奇怪的原因,您需要从服务器中动态下载JS文件以执行它,则只需要从前端托管过程中提供此文件即可。为此,不同的开发服务器具有不同的技术,但是通常您只是指定要使用的文件扩展名和路径。
编辑前端文件后,您将在浏览器中看到热填充。 来实现节点过程(从 nodemon )
您可以使用各种工具 这种操作方式不是理想的,请尝试改进它,并检查人们已经在这个方向上所做的事情。例如,您可以与
Let's improve your current flow by separating your backend API process from frontend hosting process. While backend can, it's not good in serving static html files (especially for local development purposes).
Run your backend as usual,
node index.js
. But as soon as this command will become more complicated, you will probably want to use npm scripts and do just npm start)Run separate server process for frontend. Check out parcel, snowpack, DevServer. It can be as easy as
npx parcel index.html
, but this command is likely to change frequently with your understanding of your tool features.To call backend, just add an API endpoint to an express app (just like you already did for serving static content), and call it, using backend process URL.
Usually, you will see your app on
http://localhost/
and it should do requests tohttp://localhost:8080/
.If for some strange reason you will want to dynamically download js file from your server to execute it, you just need to serve this file from your frontend hosting process. In order to do so, different development servers have different techniques, but usually you just specify file extensions and paths you want to be available.
After editing frontend files, you will see hot-reload in browser. You can achieve the same for node process with various tools (start googling from nodemon)
If you find this way of operating not ideal, try to improve it, and check what people already did in this direction. For example, you can run two processes in parallel with concurrently.