问题描述
我被屏蔽了 3 天,并在互联网上进行了研究.这是代码.
I'm blocked since 3 days and did my research on the internet. Here' is the code.
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');
});
});
输出:
管理规则禁止请求.请确保您的请求具有 User-Agent 标头 (http://developer.github.com/v3/#user-agent-required).检查 https://developer.github.com 以了解其他可能的原因.
我在这里发现了一些有用的东西:
I found something useful here:
- 在 Node.js/Express 中,我如何自动将此标头添加到每个渲染"中?回应?
- 正在请求 https://api.github.com/users (api) 返回 System.Net.HttpStatusCode.Forbidden IsSuccessStatusCode = false
但这些都不是很有帮助.
But these were not very helpful.
我试过:res.setHeader("User-Agent","My App");
但我不太确定第二个参数.
I tried: res.setHeader("User-Agent", "My App");
but I'm not very sure about the second argument.
修改了server.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');
});
你有没有遇到过这样的问题.请帮忙.
Have you ever face this kind of issue. Please help.
推荐答案
您正在为响应设置标题.相反,您必须在您进行的 API 调用中设置标头.您可以将 options
对象传递给 http.get()
方法并在那里设置标题.
You are setting headers to your response. Instead, you must set headers in the API call you make. You can pass options
object to the http.get()
method and set headers there.
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 用户代理标头的答案:
See this answer on setting github user-agent header:
https://stackoverflow.com/a/16954033/4185234
这篇关于如何使用 Express 服务器对 api.github 进行 GET 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!