在node.js与微信小程序后台数据库交互(二)html与node.js通信中,我们实现了html页面通过XMLHttpRequest将值传递给node.js服务并返回。让我们改进这个例子:page.html文件仍然使用我们在(2)中使用的相同文件。//page.jsvartest=document.getElementById('test');varbt=document.getElementById('bt');bt.onclick=function(){//varvalue=document.getElementById('username').价值;varvalue={name:"三台子小学",address:"黄河街道"}varxmlHttp=newXMLHttpRequest();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("内容类型","application/json;charset=UTF-8");xmlHttp.send(JSON.stringify(值));//对象到json};我们创建一个对象值,并将其转换成json字符串发送到6060端口,以启动node.js服务。注意:因为传递的是json数据,open和send之间要设置header参数:xmlHttp.setRequestHeader("Content-type","application/json;charset=UTF-8");以下是node.js代码://app.jsconsthostIp='127.0.0.1';常量apiPort=6060;varexpress=require('快递');varapp=express();varbodyParser=require('body-parser');应用程序。使用(bodyParser.json());//用于解析application/json//允许自定义标头和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);/让选项请求快速返回/}else{next();}});app.post('/',function(req,res){res.setHeader('Content-Type','text/plain;charset=UTF-8');//返回代理内容varrtnJSON=JSON.stringify(req.body)console.log("返回数据:"+rtnJSON)res.end(rtnJSON);});varserver=app.listen(apiPort,function(){console.log('代理接口,运行在http://'+hostIp+':'+apiPort+'/');})因为XMLHttpRequest发送的数据是json格式的,所以我们需要在express中使用body-parser进行解析:varbodyParser=require('body-parser');app.use(bodyParser.json());//对于解析application/json浏览器对ajax跨域发送数据有限制,所以添加如下代码:(这个地方折腾了好久)//allowcustomheaderandCORSapp.all('*',function(req,res,next){res.header('Access-Control-Allow-Origin','*');res.header('Access-Control-Allow-Headers','Content-Type,Content-长度,授权,接受,X-Requested-With,yourHeaderFeild');res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS');if(req.method=='OPTIONS'){res.sendStatus(200);/让选项请求快速返回/}else{next();}});最后这里express使用了post方法,而不是get方法:app.post('/',function(req,res){res.setHeader('Content-Type','text/plain;charset=UTF-8');//返回代理内容varrtnJSON=JSON.stringify(req.body)console.log("返回数据:"+rtnJSON)res.end(rtnJSON);});到这里,我们就实现了express接收json数据并发回的过程。接下来我们就可以根据查询条件接收json数据了去微信小程序后台获取数据发送给前端!!!
