简体   繁体   English

在我的JavaScript HTML源代码中执行Node.js代码

[英]Executing nodejs code in my javascript html source

I use express to send a html file to incoming GET requests: 我使用express将html文件发送到传入的GET请求:

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/index.html'));
});

In that html file I declared(not sure which word to use here) another javascript file, script.js. 在该html文件中,我声明了另一个javascript文件(script.js)(不确定在此处使用哪个词)。 via 通过

<script src="script.js"></script> in the <head> <script src="script.js"></script> <head>中的<script src="script.js"></script> <head>

Is it possible to access nodejs functions like require() in this script.js? 是否可以在此script.js中访问诸如require()类的nodejs函数?

If it is, what am I doing wrong/ what do I have to include to be able to use it? 如果是,我在做什么错/要使用它必须包括哪些内容?

Your script.js file runs in the browser and only has access to the features that a browser JS environment has. 您的script.js文件在浏览器中运行,并且只能访问浏览器JS环境具有的功能。 Since there's no built-in require() in a browser, you can't directly use require() in script.js and the same is true for other node.js functionality that is not built into a browser environment. 由于浏览器中没有内置的require() ,因此您无法在script.js直接使用require() ,并且对于未内置于浏览器环境中的其他node.js功能也是如此。

If you need access to something that can only be done on the server (like accessing a server side database), then you can create a route on your server and use an Ajax call from script.js to send a request to that route and get a response. 如果您需要访问只能在服务器上完成的操作(例如访问服务器端数据库),则可以在服务器上创建路由,并使用来自script.js的Ajax调用向该路由发送请求并获取一个答复。

For require() specifically, there are some third party libraries (not part of node.js or built into the browser) that allow you to get require-like functionality in a browser, but that's a special case. 具体来说,对于require() ,有一些第三方库(不是node.js的一部分或内置于浏览器中),使您可以在浏览器中获得类似需求的功能,但这是特例。 Other node.js functionality like fs.readFile() is simply beyond the capabilities of a browser environment. 其他node.js功能(例如fs.readFile()完全超出了浏览器环境的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM