简体   繁体   English

Node.js和HTML

[英]Node.js and HTML

I am new to and I'm trying to run a script that uses Node.js ' require() when a html button is clicked but it simply says "require" is not recognized (which makes sense). 我是新手,我正在尝试运行一个脚本,该脚本在单击html按钮时使用Node.js'require require() ,但是它只是说"require" is not recognized (这很有意义)。

So how exactly can I activate my node.js script when the HTML button is clicked in this case? 那么在这种情况下,当单击HTML按钮时,如何才能完全激活我的node.js脚本?

Thank you. 谢谢。

You could use some library like express to handle requests and responses easely. 您可以使用诸如express之类的库轻松处理requestsresponses In your case when the button is clicked a request is done to a server thats running node, the server handles the request and then sends back a response . 在你的情况下,当按钮被点击一个request是为了运行节点的服务器,多数民众赞成,服务器处理的请求,然后发回一个response

See more in Anatomy of an HTTP Transaction in Node's oficial docs. 请参阅Node.com官方文档中的HTTP事务剖析中的更多内容。

The purpose of Node.js is to write server-side code in Javascript. Node.js的目的是用Javascript编写服务器端代码。 This means that you can't use this functionality in the browser. 这意味着您不能在浏览器中使用此功能。

However, to accomplish what you were asking, you can use a framework like Express.js (a node package with Node.js) 但是,要完成您的要求,可以使用Express.js之类的框架(带有Node.js的节点包)

Then, you need to set up an ajax request from the front-end that communicates with your server. 然后,您需要从与服务器通信的前端设置ajax请求。 You can launch an asynchronous call once your button is clicked, which can be received on the back-end using Express.js 单击按钮后即可启动异步调用,可以使用Express.js在后端接收异步调用。

All you need is a module wrapper to have require feature in browser. 您只需要一个模块包装器即可在浏览器中具有require功能。

There are several tools can accomplish this task, AFAIK, the most popular of them are webpack and browserify 有几个工具可以完成这个任务,据我所知,最流行的都是的WebPackbrowserify

Webpack is complex but very strong, and has a lot of features Webpack很复杂但非常强大,并且具有很多功能

Browserify is simpler Browserify更简单

Example: 例:

yarn init
yarn add lodash
cat test.js
browserify test.js > output.js

Content of test.js test.js内容

_ = require('lodash')

console.log(_.join(['hello', 'world']))

Now you can load output.js into browser 现在您可以将output.js加载到浏览器中

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

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