69、JS中如何调用上位机接口

在JavaScript中调用上位机(主机)接口通常有以下几种方式,具体取决于你的应用场景和安全要求:

1. Web应用中的接口调用

使用Fetch API

javascript 复制代码
fetch('https://api.example.com/endpoint', {
  method: 'POST', // 或 'GET', 'PUT', 'DELETE' 等
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your_token_here'
  },
  body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

使用Axios (推荐)

javascript 复制代码
axios.post('https://api.example.com/endpoint', {
    key: 'value'
  }, {
    headers: {
      'Authorization': 'Bearer your_token_here'
    }
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

2. 浏览器扩展/桌面应用中的特殊调用

使用Chrome扩展的native messaging

javascript 复制代码
// 在background.js中
const port = chrome.runtime.connectNative('com.your_company.your_application');
port.onMessage.addListener((response) => {
  console.log("Received: " + response);
});
port.postMessage("Hello from the extension");

使用Electron应用

javascript 复制代码
const { ipcRenderer } = require('electron');

// 发送消息到主进程
ipcRenderer.send('api-call', { data: 'some data' });

// 接收主进程响应
ipcRenderer.on('api-response', (event, arg) => {
  console.log(arg);
});

3. 本地HTTP服务器接口

如果你的上位机运行了本地HTTP服务:

javascript 复制代码
// 调用本地服务
fetch('http://localhost:3000/api', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ query: 'data' })
})
.then(response => response.json())
.then(data => console.log(data));

4. WebSocket实时通信

javascript 复制代码
const socket = new WebSocket('ws://localhost:8080');

socket.onopen = function(e) {
  console.log("Connection established");
  socket.send(JSON.stringify({ command: 'getData' }));
};

socket.onmessage = function(event) {
  console.log(`Data received: ${event.data}`);
};

socket.onclose = function(event) {
  if (event.wasClean) {
    console.log(`Connection closed cleanly, code=${event.code} reason=${event.reason}`);
  } else {
    console.log('Connection died');
  }
};

socket.onerror = function(error) {
  console.log(`Error: ${error.message}`);
};

安全注意事项

  • 始终验证和清理输入数据
  • 使用HTTPS确保传输安全
  • 实现适当的错误处理
  • 考虑跨域问题(CORS),必要时在后端配置CORS头
  • 对于敏感操作,实现身份验证和授权机制

选择哪种方法取决于你的具体需求、上位机接口的类型以及应用的安全要求。

相关推荐
yanlele12 分钟前
前端面试第 78 期 - 2025.09.07 更新 Nginx 专题面试总结(12 道题)
前端·javascript·面试
影子信息26 分钟前
el-tree 点击父节点无效,只能选中子节点
前端·javascript·vue.js
徐小夕43 分钟前
用Vue3写了一款协同文档编辑器,效果简直牛!
前端·javascript·vue.js
wangbing11251 小时前
界面规范8-文字
前端·javascript·html
qczg_wxg1 小时前
高阶组件介绍
开发语言·javascript·react native·ecmascript
小菜全1 小时前
打包 Uniapp
javascript·vue.js·html5
itslife2 小时前
实现 Promise
前端·javascript
一枚前端小能手2 小时前
🔥 老板要的功能Webpack没有?手把手教你写个插件解决
前端·javascript·webpack
至善迎风2 小时前
使用国内镜像源解决 Electron 安装卡在 postinstall 的问题
前端·javascript·electron
Mintopia3 小时前
实时 AIGC:Web 端低延迟生成的技术难点与突破
前端·javascript·aigc