在node.js与微信小程序后盾数据库的交互(2)html与node.js的通信 中,咱们实现了html页面通过XMLHttpRequest传递值给node.js服务并返回。

上面咱们对该例子进行改良:
page.html文件依然应用咱们在(2)中同样的文件。

//page.jsvar test = document.getElementById('test');var bt = document.getElementById('bt');bt.onclick = function () {    //var value = document.getElementById('username').value;    var value = {name:"三台子小学",address:"黄河大巷"}    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:6060/', true);     xmlHttp.setRequestHeader("Content-type","application/json;charset=UTF-8");    xmlHttp.send(JSON.stringify(value));      //对象转json};

咱们创立一个对象value,并把它转为json字符串发送给6060端口启动的node.js服务。
留神:因为传递的是json数据,因而在open和send之间要设置头参数:

xmlHttp.setRequestHeader("Content-type","application/json;charset=UTF-8");

上面是node.js代码:

//app.jsconst hostIp = '127.0.0.1';const apiPort = 6060;var express = require('express');var app = express();var bodyParser = require('body-parser');app.use(bodyParser.json()); // for parsing application/json//allow custom header and CORSapp.all('*',function (req, res, next) {  res.header('Access-Control-Allow-Origin', '*');  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');   if (req.method == 'OPTIONS') {    res.sendStatus(200); /让options申请疾速返回/  }  else {    next();  }});app.post('/', function(req, res) {    res.setHeader('Content-Type', 'text/plain;charset=UTF-8');    //返回代理内容    var rtnJSON = JSON.stringify(req.body)    console.log("返回数据:"+rtnJSON)    res.end(rtnJSON);});var server = app.listen(apiPort, function () {  console.log('代理接口,运行于 http://' + hostIp + ':' + apiPort + '/'); })

因为XMLHttpRequest发送过去的数据是json格局,因而咱们在express中要应用body-parser来进行解析:

var bodyParser = require('body-parser');app.use(bodyParser.json()); // for parsing application/json

浏览器对ajax跨域发送数据有限度,因而加上上面的代码:(这个中央我折腾了良久)

//allow custom header and CORSapp.all('*',function (req, res, next) {  res.header('Access-Control-Allow-Origin', '*');  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');   if (req.method == 'OPTIONS') {    res.sendStatus(200); /让options申请疾速返回/  }  else {    next();  }});

最初,express在这里用的是post形式而不是get形式:

app.post('/', function(req, res) {    res.setHeader('Content-Type', 'text/plain;charset=UTF-8');    //返回代理内容    var rtnJSON = JSON.stringify(req.body)    console.log("返回数据:"+rtnJSON)    res.end(rtnJSON);});

到这里,咱们曾经实现了express接管到json数据再发回去的流程。下一步咱们就能够依据接管到的查问条件json数据到微信小程序后盾获取数据再发送给前端啦!!!