用于调用REST API的Nodejs和Express代理设置
我正在调用“ themoviedb”的REST API,当我通过办公室网络发出请求时,出现如下错误:
{ “错误号”: “ETIMEDOUT”, “代码”: “ETIMEDOUT”, “系统调用”: “连接”, “地址”: “54.164.67.128”, “端口”:443}
当我通过家庭网络发出请求时,我得到了预期的结果。我知道我必须启用代理设置,但是我不知道该怎么做,或者我必须在系统或代码中进行设置。请帮忙。我的代码如下:
const apiKey = "----tmdb API KEY----";
const https = require("https");
const { URL }= require('url');
function getMovieByID(id, callback){
console.log("Inside getMovieByID ID: "+ id);
var options = new URL("/"+id+"?api_key="+apiKey);
var req = https.request(options, function (res) {
let chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
let body = Buffer.concat(chunks);
callback(null, body.toString());
});
});
req.on("error", function(err) {
callback(err, null);
});
req.end();
};
getMovieByID("75780", (err,data) =>{
var temp ="";
if (err != null){
console.log("Error:", JSON.stringify(err));
process.exit()
}else{
//console.log("Movies:\n",data);
temp = data
}
console.log("Result:\n", temp)
process.exit()
});
回答如下:尝试此
var https = require('https');
var ProxyAgent = require('proxy-agent');
var url = "https://api.themoviedb/3/movie/"+id+"?api_key="+apiKey
// HTTP, HTTPS, or SOCKS proxy to use
var proxyUri = process.env.http_proxy || "http://" + user + ":" + password + "@" + host + ":" + port;;
var opts = {
agent: new ProxyAgent(proxyUri)
};
// the rest works just like any other normal HTTP request
https.get(url,opts,function(res){
});