节点js捕获标题并对其执行某些操作

时间:2016-09-25 14:26:15

标签: node.js

您好我是Node js的新手,我正在开发一个简单的应用程序,但是当我尝试发出请求从响应中获取某个标头时,我偶然发现了一个问题。问题是每当我启动请求时它会进行无限次调用,而我的服务器崩溃。

这是我的代码

var request  = require('request'),
    url = require('url');

module.exports = function(req, res) {
    req.pathName = req.pathName || url.parse(req.url).pathname;

    var path = '';

    if(req.pathName !== '/content/style.css') {
        path = req.pathName;
    }

    var options = {
        url: 'http://localhost:7357' + path,
        method: 'HEAD'
    }

    request(options,function(err, response) {
        if (!err && response.statusCode == 200) {
            if(response.headers.statusheader && response.headers.statusheader === 'Full') {
                console.log('do something');
                return true;
            }
        }
    });
}

我在 homepage.js 文件中设置了一个标题

var fs = require('fs'),
    url = require('url');

module.exports = function(req, res) {
    req.pathName = req.pathName || url.parse(req.url).pathname;

    if(req.pathName === '/') {
        fs.readFile('./index.html', function(err, data) {
            if(err) {
                console.log(err);
            }

            res.writeHead(200, {
                'Content-Type': 'text/html',
                'StatusHeader': 'Full'
            });
            res.write(data);
            res.end();
        });
    } else {
        return true;
    }
}

以下是我如何调用每个模块

var favicon = require('./favicon'),
    homepage = require('./homepage'),
    upload = require('./upload'),
    gallery = require('./gallery'),
    details = require('./details'),
    catch_header = require('./catch_header'),
    normal = require('./normal');

module.exports = [favicon, catch_header, homepage, upload, gallery, details, normal];

var http = require('http'),
    fs = require('fs'),
    url = require('url'),
    handlers = require('./handlers/main');

http.createServer(function(req, res) {
        for(var handler of handlers) {
            var proceed = handler(req, res);

            if(!proceed) {
                break;
            }
        }
    })
    .listen(7357);

所以我的问题是这个问题的解决方法是什么,如何防止我的服务器崩溃

0 个答案:

没有答案