关于html:nodejs与微信小程序后台数据库的交互2html与nodejs的通信

1次阅读

共计 1404 个字符,预计需要花费 4 分钟才能阅读完成。

咱们的目标是制作基于高德地图 API 的地图数据编辑工具,地图编辑页面应该是 html+js 的,因为基于 vue 封装欠缺的高德地图组件目前还没有。

html 如何与 node.js 通信呢?解决了这一问题,咱们就能够将在 html 中调用高德 API 采集的坐标数据传递给 node.js server,再通过 node.js 调用微信小程序数据 API 来保留或读取小程序数据库。

看下上面的例子:

//page.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <input type="text" id="username" placeholder="请输出用户名">
    <button id="bt"> 提交 </button>
    <h1 id="test"></h1>

    <script src="page.js"></script>
</body>

</html>

援用的 page.js:

//page.js
var test = document.getElementById('test');
var bt = document.getElementById('bt');

bt.onclick = function () {var value = document.getElementById('username').value;
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange=function()
    {if (xmlHttp.readyState==4 && xmlHttp.status==200)
        {test.innerHTML = xmlHttp.responseText;}
    };

    xmlHttp.open('POST', 'http://127.0.0.1:3000/', true); 
    xmlHttp.send(value);      // 把 input 框中的 value 发送过来
};

留神:下面的 page 页和 node.js 无关,咱们能够用 tomcat 来进行公布。
接下来咱们在 http://127.0.0.1:3000/ 的端口创立一个 node.js 服务:

//app.js
var http = require('http');

var server = http.createServer(function (req, res) {
    var body = '';
    req.on('data', function(data) {// 接管客户端发送过去的数据,也就是 xmlHttp.send(value);
        body += data;
    });

    req.on('end', function() {
        res.writeHeader(200, {
            'Content-Type': 'text/plain',
            'Access-Control-Allow-Origin': '*'    // 解决跨域问题
        });
        res.write("hello:" + body);
        res.end();})
});

server.listen(3000, function () {console.log('server start at localhost:3000');
});

首先命令行启动 node.js 服务:

node app.js

而后在浏览器里拜访网址 127.0.0.1:3000
在页面的文本框里输出名字,页面显示 hello 名字:

正文完
 0