我正在尝试使用NodeJS(使用Express)向外部API发出HTTP GET请求,但没有返回任何数据。我的代码是下一个:
import * as http from "http";
const options = {
host: "EXAMPLE.COM",
path: "/MY/PATH",
headers: {
"Content-Type": "application/json",
"Authorization": "Basic XXXXXXXXXXXXXXXXXX"
}
};
const req = http.get(options, function(res) {
console.log("statusCode: " + res.statusCode);
res.on("data", function (chunk) {
console.log("BODY: " + chunk);
});
});
但是我得到的答复是: 状态码:302 和 BODY 为空。
外部API正常工作(我尝试使用INSOMNIA执行http GET请求并返回数据)
我正在执行的请求 NEEDS 授权令牌
我在做什么错?或我该怎么做才能取回数据?
欢呼
答案 0 :(得分:-2)
您只是将数据扔到console.log而没有响应请求。
您没有提到节点上使用的是什么http服务器。如果您使用的是express.js(最常见的一种),则应该具有以下内容:
const express = require("express");
const app = express();
const port = 3003;
const http = require("http");
// your webserver url localhost:3003/fetch-something
app.get("/fetch-something", (req, res) => {
const options = {
host: "EXAMPLE.COM",
path: "/MY/PATH",
headers: {
"Content-Type": "application/json",
Authorization: "Basic XXXXXXXXXXXXXXXXXX"
}
};
const httpReq = http.get(options, function(httpRes) {
//output status code to your console
console.log("statusCode: " + httpRes.statusCode);
httpRes.on("data", function(chunk) {
// still nothing happens on client - this will also just print to server console
console.log("data", chunk);
// return some data for requested route
return res.send(chunk);
});
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));