使用Node.js中的Express框架来创建本地服务器,然后定义应用程序的路由和处理程序来处理来自本地应用的命令和请求。
以下是一个简单的示例,用于处理来自本地应用的POST请求:
const express = require('express');
const app = express();
// Body-parser中间件用于解析POST请求的JSON数据
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// 定义一个路由来处理来自本地应用的POST请求
app.post('/command', (req, res) => {
// 获取命令参数
const command = req.body.command;
// 根据命令执行逻辑
if (command === 'doSomething') {
// 执行doSomething的逻辑
res.send('Success');
} else {
res.status(400).send('Unknown command');
}
});
// 启动本地服务器
app.listen(3000, () => {
console.log('Server started on port 3000');
});
在本地应用中,使用HTTP客户端来发送POST请求:
const http = require('http');
const postData = JSON.stringify({ command: 'doSomething' });
const options = {
hostname: 'localhost',
port: 3000,
path: '/command',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', (chunk) => {
console.log(`body: ${chunk}`);
});
});
req.on('error', (error) => {
console.error(error);
});
req.write(postData);
req.end();