The frontend and business layer communicate through the following three methods, which can be used in combination according to your needs:
- ipc
- http/https
- socket
IPC
Advantage: Bidirectional communication
File: Frontend imports ipcRender.js
One-way Communication
# Define a communication channel, i.e., route
const ipcApiRoute = {
hello: 'controller/example/hello',
}
# Send request
# This request will access the hello function in the controller/example.js file
import { ipc } from '@/utils/ipcRenderer';
ipc.invoke(ipcApiRoute.hello, {name:'Zhang San'}).then(r => {
// r is the returned data
conson.log(r);
})Bidirectional Communication
# Define a communication channel, i.e., route
const ipcApiRoute = {
ipcSendMsg: 'controller/example/ipcSendMsg',
}
// Avoid duplicate listeners, or put the $ipc.on() functionality in a unified place that is only loaded once
ipc.removeAllListeners(ipcApiRoute.ipcSendMsg);
// Listen and receive data sent by the server via event.reply()
ipc.on(ipcApiRoute.ipcSendMsg, (event, result) => {
console.log('[ipcRenderer] [ipcSendMsg] result:', result);
self.messageString = result;
// Call another backend interface
event.sender.send(ipcApiRoute.hello, 'electron-egg');
})
// Send request to the server
ipc.send(ipcApiRoute.ipcSendMsg, 'parameters')Preload Module Communication
# Send message to the frontend
// Channel
const channel = 'controller/example/ipcSendMsg';
// Use the main window's webContents.send() method
mainWindow.webContents.send(channel, {name:'Zhang San'});IPC communication documentation
- ipcMain: Documentation
- ipcRenderer: Documentation
HTTP/HTTPS
Advantage: Can access EE programs cross-platform from frontend, browser, terminal commands (curl), etc.
Generate SSL certificates: View
Open Configuration File
/* Built-in http service */
httpServer = {
enable: false, // Whether to enable
port: 7071, // Default port (if the port is in use, a random one is obtained)
};cors Property
- origin
Configure the Access-Control-Allow-Origin CORS header, string or function, which takes ctx as the first parameter
- exposeHeaders
Configure the Access-Control-Expose-Headers CORS header, type: Array
- maxAge
Configure the Access-Control-Max-Age CORS header, type: Number
- credentials
Configure the Access-Control-Allow-Credentials CORS header. Type: Boolean.
- allowMethods
Configure the Access-Control-Allow-Methods CORS header. Type: array, default value ['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
- allowHeaders
Configure the Access-Control-Allow-Headers CORS header. Type: Array
{
origin: function(ctx) {
if (ctx.url === '/test') {
return false;
}
return '*';
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}body Property
- patchNode {Boolean} Patch the request body to Node's ctx.req, default: false
- patchKoa {Boolean} Patch the request body to Koa's ctx.request, default: true
- jsonLimit {String|Integer} JSON body size limit, default: 1mb
- formLimit {String|Integer} Form body size limit, default: 56kb
- textLimit {String|Integer} Text body size limit, default: 56kb
- encoding {String} Set the encoding for incoming form fields, default: utf-8
- multipart {Boolean} Parse multipart bodies, default: false
- urlencoded {Boolean} Parse urlencoded bodies, default: true
- text {Boolean} Parse text bodies, such as XML, default: true
- json {Boolean} Parse JSON bodies, default: true
- jsonStrict {Boolean} Toggle co-body strict mode; if set to true - only parse arrays or objects, default: true
- includeUnparsed {Boolean} Toggle co-body returnRawBody option; if set to true, for form-encoded and JSON requests the original, unparsed body is attached to ctx.request.body using a Symbol, default: false
- formidable {Object} See below
- onError {Function} Custom error handler, if an error is thrown, you can customize the response - onError(error, context), default will throw
- strict {Boolean} DEPRECATED If enabled, do not parse GET, HEAD, DELETE requests, default: true
- parsedMethods {String[]} Declare the HTTP methods in which entities will be parsed, default: ['POST', 'PUT', 'PATCH']. Replaces the strict optionAbout
About the formidable object
- maxFields {Integer} Limit the number of fields that the querystring parser will decode, default: 1000
- maxFieldsSize {Integer} Limit the amount of memory all fields (excluding files) can allocate in bytes, if exceeded, an 'error' event will be triggered, default: 2mb (2 * 1024 * 1024)
- uploadDir {String} Set the directory for file uploads, default: os.tmpDir()
- keepExtensions {Boolean} Files written to uploadDir will include the original file's extension, default: false
- hashAlgorithm {String} If you want to calculate checksums for incoming files, set it to "sha1" or "md5", default: false
- multiples {Boolean} Whether to upload multiple files, default: true
- onFileBegin {Function} Special callback when a file begins. This function will be executed by formidable and can be used to rename files before saving them to disk.
Usage
# Frontend, there is a demo in the project.
# Terminal command, e.g.
curl http://127.0.0.1:7071/controller/example/doHttpRequest?id=pictures
# The controller in the route can be removed
curl http://127.0.0.1:7071/example/doHttpRequest?id=pictures
# Add an api directory layer in the controller
curl http://127.0.0.1:7071/api/test/hello
# Browser
http://127.0.0.1:7071/controller/example/doHttpRequest?id=picturesSocket
Advantage: Bidirectional communication
Open Configuration File
/* Built-in socket service */
socketServer = {
enable: false, // Whether to enable
port: 7070, // Default port (if the port is in use, a random one is obtained)
};Usage
Method One
Call from frontend to access the electron business layer
import { ipcApiRoute } from '@/api';
import { io } from 'socket.io-client';
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
const currentStatus = ref('Closed');
const servicAddress = ref('ws://localhost:7070');
const client = {
socket: null
};
onMounted(() => {
init()
})
function init() {
client.socket = io(servicAddress.value);
client.socket.on('connect', () => {
console.log('connect!!!!!!!!');
currentStatus.value = 'Open';
});
}
function sendRequest(id) {
if (currentStatus.value == 'Closed') {
message.error('socketio service is not started');
return;
}
const method = ipcApiRoute.framework.doSocketRequest;
client.socket.emit('socket-channel', { cmd: method, args: {id} }, (response) => {
// response is the returned value
console.log('response:', response)
});
}Method Two
Use socket.io in another Node.js project to communicate with the EE framework
# Third-party project imports socket client
const Client = require('socket.io-client');
// socket supports both http protocol and websocket protocol
// WebSocket is recommended
const url = 'http://127.0.0.1:' + port;// Port configured in config
const cObj = Client(url);
const channel = 'socket-channel'; // Communication channel is fixed
const method = 'controller/example/hello'; // Method in the controller of the EE framework
cObj.emit(channel, { cmd: method, params: 1 }, (response) => {
// response is the returned value
});Method Three
Network modules in other languages are largely similar, just listen to the communication address
