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

如何使用Express向api.github发起GET请求并解决403禁止访问问题

问题原因

你添加User-Agent的位置错误:你将该头加到了Express返回给前端用户的响应头中,但实际需要携带User-Agent的是你的Node服务向GitHub API发起的出站请求,GitHub校验的是这个请求的头信息。

解决方案

直接修改api.js中调用https.get的逻辑,给GitHub的请求配置headers参数即可:

const express = require('express');
const router = express.Router();
var http = require('http');
var https = require("https");

router.get('/github', async function (req, res) {
    https.get('https://api.github.com/v3/users/tmtanzeel', {
        headers: {
            // 取值无强制规范,填写任意非空标识字符串即可
            'User-Agent': 'My-GitHub-Query-App'
        }
    }, function (apiRes) {
        apiRes.pipe(res);
    }).on('error', (e) => {
        console.error(e);
        res.status(500).send('Something went wrong');
    });
});

补充说明

你之前在server.js中间件里添加的res.setHeader("User-Agent", "My App");没有作用,可以删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:48:01