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

使用字符串插值与Fetch()调用GitHub API获取用户信息遇CORS问题

GitHub API调用CORS错误排查与解决

问题现象

调用GitHub API根据用户名获取用户信息时,反复触发CORS相关错误:

Access to fetch at 'https://api.github.com/users/' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
pull.js:7

GET https://api.github.com/users/ net::ERR_FAILED
getUser @ pull.js:7
oninput @ (index):17
pull.js:7

Uncaught (in promise) TypeError: Failed to fetch
at getUser (pull.js:7:11)
at HTMLInputElement.oninput ((index):17:101)

代码详情

HTML部分

<div class="container">
<div class="flex justify-space">
<div class="text-space" id="scroll-container">
<ul id="note"> </ul>
</div>
</div>
</div>

JavaScript部分

const query_search = document.getElementById('search').value

const access_token = ''
const final_url = `https://api.github.com/users/${query_search}`

async function getUser() {
    await fetch(final_url, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': `token ${access_token}`,
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'content-type'
        }
    })
    .then((res) => res.json())
    .then((data) => 
    document.getElementById('note').innerHTML = (data))
}

解决步骤

  1. 移除错误的请求头
    Access-Control-Allow-Origin 和 Access-Control-Allow-Headers 是服务器返回给浏览器的响应头,不需要在前端请求里添加。把这两个字段从fetch的headers中删除,这是预请求失败的直接原因。

  2. 修正URL拼接时机
    当前代码在页面加载时就获取输入框值,此时输入框为空,导致请求URL变成https://api.github.com/users/(无用户名)。需要把输入值的获取放到getUser函数内部,确保每次调用拿到最新输入:

    async function getUser() {
        const query_search = document.getElementById('search').value
        const final_url = `https://api.github.com/users/${query_search}`
        // 后续fetch逻辑...
    }
    
  3. 优化数据渲染逻辑
    直接把对象赋值给innerHTML会显示[object Object],需要转换成可读格式,比如提取具体字段或转成JSON字符串:

    .then((data) => {
        document.getElementById('note').innerHTML = `
            <li>用户名: ${data.login}</li>
            <li>昵称: ${data.name || '无'}</li>
            <li><img src="${data.avatar_url}" width="100" alt="${data.login}"></li>
        `
    })
    
  4. 添加输入校验与错误捕获
    避免空请求,同时处理请求失败的情况:

    async function getUser() {
        const query_search = document.getElementById('search').value.trim()
        if (!query_search) {
            document.getElementById('note').innerHTML = '<li>请输入GitHub用户名</li>'
            return
        }
        const final_url = `https://api.github.com/users/${query_search}`
        try {
            const res = await fetch(final_url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Authorization': `token ${access_token}` // 无token可删除该字段
                }
            })
            if (!res.ok) throw new Error('用户不存在或请求失败')
            const data = await res.json()
            document.getElementById('note').innerHTML = `
                <li>用户名: ${data.login}</li>
                <li>昵称: ${data.name || '无'}</li>
                <li>公开仓库数: ${data.public_repos}</li>
                <li><img src="${data.avatar_url}" width="100" alt="${data.login}"></li>
            `
        } catch (err) {
            document.getElementById('note').innerHTML = `<li>错误: ${err.message}</li>`
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:05:25