我对 Node js 非常陌生,决定学习如何保护 api key ,我已经到处寻找但找不到示例。但我发现一些建议唯一的方法是执行服务器端 api 请求。
我在这段代码中使用 openweathermap api,我在 Chrome 网络选项卡中得到了预期的数据作为响应,但我对此有疑问。
- 如何使用响应数据(例如获取当前天气、温度)?
- 这是在 Node.js 中执行服务器端 api 请求的正确方法吗?
http.createServer(function(req, res) {
if (req.url === '/') {
res.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream(__dirname + '/index.html').pipe(res);
} else if (req.url === '/getweather') {
var weatherApiURL = 'https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=<API KEY>';
request(weatherApiURL, function (error, response, body) {
if (error) {
res.writeHead(500, 'Weather API request failed', {'content-type': 'text/plain'});
res.end();
} else {
res.writeHead(200, {'content-type': 'application/json'});
res.end(body);
}
});
} else {
res.end('not found')
}
}).listen(8080);
正面:
function requestWeatherData() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/getweather', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
console.log(this.responseText);
};
xhr.send();
};
提前谢谢您!!
最佳答案
第 1 部分:如何使用数据。
您要做的第一件事是检查请求是否成功
if (this.status !== 200) {
// The request did not work.
throw new Error('Cannot use data.');
}
验证请求状态后,您需要“解析”响应。
const weatherData = JSON.parse(this.responseText);
// Lets see the js object:
console.log(weatherData);
现在您可以对数据执行任何您需要的操作。
完整示例:
function requestWeatherData() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/getweather', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function () {
if (this.status !== 200) {
// The request did not work.
throw new Error('Cannot use data.');
}
const weatherData = JSON.parse(this.responseText);
// Lets see the js object:
console.log(weatherData);
};
xhr.send();
};
第 2 部分:有正确的方法吗?
现在,我对此还不够了解,无法肯定地说,但是,您可能需要考虑以下一些问题。
- 大多数 API 都有速率限制,这意味着您可能希望尝试将请求“缓存”到某处,以减少“轮询”API 的需要
- 其他人可以在他们的应用程序中使用您公开的网址。
- 对于大型应用程序来说,按照当前的方式编写所有路由将变得非常令人头疼,对于中小型应用程序,我可以根据经验推荐 Express。
关于javascript - 如何正确执行服务器端 api 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48792892/