每个用户请求后如何清理nodejs响应?

时间:2019-10-19 14:11:53

标签: node.js

每次用户输入我们的URL时,他都会得到上一个用户的响应+他的新响应。 我是nodejs的新手,我认为我不了解该服务器的工作方式:)

无论如何,您可以在这里看到该应用程序: https://s1-nodejs.herokuapp.com (您需要重新加载页面才能在每次重新加载时看到重复的响应)。

这是我部署到Heroku的代码:

const start = Date.now();
// using the http module
var http = require('http');
var https = require('https');
var request = require('request');

var domain;
var apiKey = 'example';
var domainResultJson = [];
var promises = [];


// look for PORT environment variable, 
// else look for CLI argument,
// else use hard coded value for port 8080
port = process.env.PORT || process.argv[2] || 8080;

// create a simple server
let server = http.createServer(function (req, res) {

    for (var i = 0 ; i < 10 ; i++  ) {
        var domain = 'example-'+i+'.com';

        promises.push(CheckIfDomainAvailable(https,domain,apiKey,domainResultJson));
    }

    Promise.all(promises).then(function(values) {
        //console.log(values);

        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');

        for (var i in values) {
            val = values[i];
            res.write(val);
        }
        res.end();
    }).catch(
        console.error
    );

    function CheckIfDomainAvailable(https,domain,apiKey,domainResultJson) {
        return new Promise(function (success, failure) {
            request('https://example.com/api/v1?'
                + 'apiKey=' + apiKey + '&d=' + domain + '', function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    domainResultJson.push('1');
                    success(body);
                } else {
                    failure(error);
                }
            });
        });
    }

});

// listen on the port
server.listen(port, function () {

    console.log('app up on port: ' + port);

});

1 个答案:

答案 0 :(得分:1)

尝试在let promises = [];内声明function (req, res) { ... },如下所示:

// ...
let server = http.createServer(function (req, res) {
    let promises = []; // <= Define promises container here.

    for (var i = 0 ; i < 10 ; i++  ) {
        var domain = 'example-'+i+'.com';

        promises.push(CheckIfDomainAvailable(https,domain,apiKey,domainResultJson));
    }
// ...