27、electron 开启本地http服务
electron 开启本地http服务,让第三方可以直接通过webapi的方式访问
1、新建server.js
1 const os = require('os'); 2 const http = require('http'); 3 4 5 let server; 6 7 function openServer() { 8 // 防止重复开启 9 closeServer(); 10 11 // 获取本机的局域网IP和自定义端口 12 let SERVER_PORT = 65526; 13 let SERVER_IP = getServerIp(); //返回127.0.0.1访问的直接http://localhost:65526 14 15 server = http.createServer(); 16 server.on('request',(req,res)=>{ 17 res.writeHead(200,{ "Content-Type": "application/json;charset=utf-8", "access-control-allow-origin": "*" }); 18 19 // 监听 '/api/authentication' 20 if(req.method === "POST" && req.url ==="/api/authentication"){ 21 let context = { 22 code: 200, 23 data: { type: 'Hello World!' } 24 } 25 res.end(JSON.stringify(context)); 26 } 27 else if(req.method ==="GET"){ 28 let context = { 29 code: 200, 30 data: { type: 'GET' } 31 } 32 res.end(JSON.stringify(context)); 33 //res.end(test()); 34 } 35 }); 36 37 // 返回端口开启结果 38 return new Promise((resolve,reject)=>{ 39 server.listen(SERVER_PORT,SERVER_IP,()=>{ 40 // 服务器正确开启 41 resolve(`服务器开启成功,服务器地址: http://${SERVER_IP}:${SERVER_PORT}`) 42 }); 43 server.on("error",(err)=>{ 44 if(err.code === 'EADDRINUSE'){ 45 reject(`端口:${SERVER_PORT}被占用,请更换占用端口`) 46 } 47 }); 48 49 }); 50 51 } 52 53 function closeServer(){ 54 server && server.removeAllListeners(); 55 server && server.close(()=>{ 56 console.log("服务接口关闭"); 57 }); 58 } 59 60 61 // 获取本机的局域网IP 62 function getServerIp() { 63 return "127.0.0.1"; // 64 65 let interfaces = os.networkInterfaces(); 66 for (let devName in interfaces) { 67 let iface = interfaces[devName]; 68 for (let i = 0; i < iface.length; i++) { 69 let alias = iface[i]; 70 if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) { 71 return alias.address; 72 } 73 } 74 } 75 } 76 77 78 module.exports = { //注意node的导出方式是module.exports 或exports 79 openServer, 80 closeServer 81 }
2、在index.js里面引入server.js并开启服务
let {openServer} = require("./server.js"); //开启本地http服务
//开启服务 openServer().then(res=>{ console.log("返回:"+res); }).catch((e)=>{ dialog.showErrorBox("提示信息",e); });
3、启动程序,打开浏览器访问http://localhost:65526/,post的方式通过postman调试也正常