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

下面我们对该例子进行改进:
page.html文件仍然使用我们在(2)中同样的文件。

//page.js
var 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.js
const 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 CORS
app.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 CORS
app.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数据到微信小程序后台获取数据再发送给前端啦!!!


娄靖宇
13 声望0 粉丝