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

为何前端代码未识别服务器的Access-Control-Allow-Origin响应头?

解决CORS预检失败及GET请求相关问题

核心问题分析

  • OPTIONS请求处理器仅设置了响应头,但未发送响应,导致浏览器收不到带CORS头的预检结果,触发跨域拦截。
  • 客户端GET请求设置Content-Type: application/json并携带请求体,不符合HTTP规范(GET请求不应携带请求体),这不仅触发了预检,还导致服务器GET接口无法正确获取数据。

1. 修复OPTIONS请求处理器

在OPTIONS回调末尾添加响应发送逻辑,确保浏览器收到合法的预检响应:

app.options("/", (req, res) => {
    res.set('Access-Control-Allow-Origin', "http://localhost:8000")
    res.set('Access-Control-Allow-Methods', "GET")
    res.set('Access-Control-Allow-Headers', "Content-Type")

    console.log(`options: ${req.body}`)
    res.sendStatus(200); // 必须发送响应,否则浏览器认为预检失败
})

2. 修正客户端请求逻辑

方案一:改用GET查询参数传递数据(符合HTTP规范)

const XML = new XMLHttpRequest()
// 通过URL查询参数传递请求信息
XML.open("GET", "http://localhost:8008?request=Identifier")
XML.send()

方案二:改用POST请求传递复杂数据(推荐)

如果需要传递结构化数据,POST才是正确的HTTP方法:

const XML = new XMLHttpRequest()
XML.open("POST", "http://localhost:8008")
XML.setRequestHeader('Content-Type', "application/json")
XML.send(JSON.stringify({
    "request": "Identifier"
}))

3. 调整服务器接口逻辑

若坚持使用GET请求

需通过查询参数获取数据,同时修复SQL语句错误并避免注入风险:

app.get("/", (req, res) => {
    res.set('Access-Control-Allow-Origin', "http://localhost:8000")
    res.set('Content-Type', "application/json")

    // 从查询参数中获取请求数据
    const { request, id } = req.query;

    console.log(req.query)

    if (request === "Identifier") {
        maxID++
        // 修复SQL插入语句,使用参数化查询避免注入
        database.run(`INSERT INTO main (Identifier, PlaybackStatus) VALUES (?, ?)`, [maxID, null], (err) => {
            if (err) return res.status(500).json({ code: 500, message: err.message })
            res.json({ code: 200, data: maxID })
        })
    } else if (request === "PlaybackStatus") {
        if (!id) return res.status(400).json({ code: 400, message: "Expected identifier" })
        // 参数化查询防止SQL注入
        database.get(`SELECT PlaybackStatus FROM main WHERE Identifier = ?`, [id], (err, row) => {
            if (err) return res.status(500).json({ code: 500, message: err.message })
            res.json({ code: 200, data: row?.PlaybackStatus || null })
        })
    } else {
        res.status(400).json({ code: 400, message: "Invalid request type" })
    }
})

若改用POST请求

只需将app.get改为app.post,即可正常通过req.body获取数据,同时保留现有CORS头设置即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:40:20