咱们的目标是制作基于高德地图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.jsvar 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.jsvar 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 名字: