如何正确执行服务器端api请求?

时间:2018-02-14 17:19:54

标签: javascript node.js

我对节点js非常新,并决定学习如何保护api密钥,我已经到处寻找,但无法找到一个例子。但我发现一些建议唯一的方法是做服务器端api请求。

我正在使用openweathermap api获取此代码,我在chrome网络选项卡中将预期数据作为响应返回,但我对此有疑问。

  1. 如何使用响应数据(例如获取当前天气,温度)?
  2. 这是在node.js中执行服务器端api请求的正确方法吗?
  3. 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 个答案:

答案 0 :(得分:0)

第1部分:如何使用数据。

您要做的第一件事就是检查请求是否成功

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(); 
};

第2部分:有没有正确的方法呢?

现在,我对此肯定不够了解,但是,这里有一些您可能想要考虑的问题。

  1. 大多数API都有速率限制,这意味着您可能希望尝试在某处“缓存”请求以减少“轮询”API的需要
  2. 其他人可以在申请中使用您的公开网址。
  3. 目前编写所有路线对于大型应用程序来说将成为一个真正令人头痛的问题,我建议从中小型应用程序中体验快递。