You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地电脑与树莓派通信的CORS问题排查求助

本地树莓派NodeJS服务器与前端网页连接问题解决

仅在本地电脑与树莓派之间建立连接,设备绝不接入公网。树莓派端运行NodeJS服务器,接收POST请求以触发GPIO操作;本地电脑运行网页UI,通过fetch()发送请求,流程如下:

COMP -> fetch() ===> PI -> GPIO

出现CORS问题导致无法连接服务器,无需了解CORS原理,仅排查请求发送或服务器处理的参数问题。

前端JS代码片段

function postState(value) {
  const options = {
    method: 'POST',
    body: JSON.stringify({ state: value }),
    headers: {
      'Content-Type': 'application/json'
    },
  };

  fetch(TOGGLE_URL, options)
    .then(res => res.json())
    .then(res => console.log(res))
    .catch(err => console.error(err));
}

服务器JS代码

require('dotenv').config();

const express = require('express');
const app = express();

const port = process.env.API_PORT;


// api
app.post('/toggle', (req, res) => {
  const state = req.query.state;
  console.log('state from body:', state);


  res.writeHead(
    200,
    {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': '*',
      'Access-Control-Request-Method': 'GET,POST',
    }
  );
});


// setup + startup
app.use(express.json());

app.listen(port, () => {
  console.log(`Listening on port ${ port }`);
});

错误信息

跨源请求被阻止:同源策略不允许读取远程资源 http://192.168.68.75:6464/toggle。(原因:CORS 请求未成功)。状态码:(null)。

解决方法

最终通过使用cors中间件解决,在服务器代码中添加以下内容:

const cors = require('cors');
app.use(cors());

兼容性问题

问题解决后发现Firefox存在兼容性问题,Safari和Chrome可正常调用接口。

内容的提问来源于stack exchange,提问作者jansensan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 09:57:10