乐趣区

关于node.js:nodejs与微信小程序后台数据库的交互4改进后的html与nodejs通信

在 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 数据到微信小程序后盾获取数据再发送给前端啦!!!

退出移动版