如何使用 Express 服务器对 api.github 进行 GET 调用

2023-12-02

我已经被封锁三天了,并在互联网上进行了研究。这是代码。

api.js

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', function (apiRes) {
        apiRes.pipe(res);

    }).on('error', (e) => {
        console.error(e);
        res.status(500).send('Something went wrong');
    });
});

Output:

行政规则禁止的请求。请确保您的请求具有 User-Agent 标头(http://developer.github.com/v3/#user-agent-required)。查看https://developer.github.com对于其他可能的原因。

我在这里发现了一些有用的东西:

  1. 在 Node.js/Express 中,如何自动将此标头添加到每个“渲染”响应中?
  2. 请求 https://api.github.com/users (api) 返回 System.Net.HttpStatusCode.Forbidden IsSuccessStatusCode = false

但这些并没有多大帮助。

我试过:res.setHeader("User-Agent", "My App");但我不太确定第二个论点。

修改的服务器.js

const express = require('express');
const app = express();
const api = require('./routes/api');
const cors = require('cors');
app.use(cors());

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    res.setHeader("User-Agent", "My App"); // <-------------ADDED HEADER HERE

    // Pass to next layer of middleware
    next();
});

app.use('/api', api);
app.get('/', function (req, res) {
    res.send('Server is up and running!');
})

app.listen(3000, function () {
    console.log('Server listening on 3000 port');
});

你有没有遇到过这样的问题。请帮忙。


您正在为您的响应设置标头。相反,您必须在进行的 API 调用中设置标头。你可以通过options反对http.get()方法并在那里设置标题。

router.get('/github', async function (req, res) {

    const options = {
       hostname: 'api.github.com',
       path: '/v3/users/tmtanzeel',
       headers: {
           'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1521.3 Safari/537.36'
       }
    }

    https.get(options, function (apiRes) {
        apiRes.pipe(res);

    }).on('error', (e) => {
        console.error(e);
        res.status(500).send('Something went wrong');
    });
});

请参阅有关设置 github 用户代理标头的答案:

https://stackoverflow.com/a/16954033/4185234

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Express 服务器对 api.github 进行 GET 调用 的相关文章

随机推荐