在Node.js和Html之间传递数据

我怎样才能将“网站”的variables从html网站传递到node.js?

我的HTML页面:search.html

<html> <body> <div id="content"> <p>Name:</p> <input id="begriff" type="name" name="" value=""> <button style="margin-top: 50px;" onclick="information()" >send</button> </div> <script type="text/javascript"> var term; function information() { term = document.getElementById("name").value; } </script> </body> </html> 

我的Node.JS:app.js我想用“term”variablessearchPlaystore中的应用程序,并将信息返回给html并打印到某处。

 var gplay = require('google-play-scraper'); gplay.search({ term: "Html 'Term' variable", num: 1, fullDetail: false, price: "free" }).then(console.log, console.log); 

你想要做的是build立一个服务器,将采取请求,执行search,并发回结果。 Express是这样做的stream行框架。

 var gplay = require('google-play-scraper'); var express = require('express'); var app = express(); app.get('/search', function (req, res) { // This will run every time you send a request to localhost:3000/search var term = req.params.term; gplay.search({ term: term, num: 1, fullDetail: false, price: "free" }).then(function(result) { // Process the result however you want. // To send a response back, do this: res.send("Whatever you want to send back"); }); }) // Tell Express what port to listen on app.listen(3000); 

当Node.js程序正在运行时,HTML页面中的JavaScript代码可以使用fetch函数向其发送请求并获取响应。

 function information() { var term = document.getElementById("begriff").value; // The id of your input was "begriff", not "name" var url = 'http://localhost:3000/search?term=' + term; // Now send a request to your Node program fetch(url).then(function(res) { // Res will be a Response object. // Use res.text() or res.json() to get the information that the Node program sent. }); } 

获得Response对象后,可以处理其中包含的信息并将其显示在页面中。