我对节点js非常新,并决定学习如何保护api密钥,我已经到处寻找,但无法找到一个例子。但我发现一些建议唯一的方法是做服务器端api请求。
我正在使用openweathermap api获取此代码,我在chrome网络选项卡中将预期数据作为响应返回,但我对此有疑问。
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();
};
先谢谢你!!
答案 0 :(得分:0)
您要做的第一件事就是检查请求是否成功
if (this.status !== 200) {
// The request did not work.
throw new Error('Cannot use data.');
}
验证了requset状态后,您需要“解析”响应。
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();
};
现在,我对此肯定不够了解,但是,这里有一些您可能想要考虑的问题。