获取响应主体并修改其内容节点js

时间:2016-07-28 14:38:06

标签: node.js express filter connect middleware

我希望在将响应主体发送到浏览器之前对其进行修改。我找到了下面的代码。如果我给网址提供路径名,例如http:// www.google.com,我就可以获得完整的响应正文。但是,如果我给 " http://localhost:3000/login'我无限次地获得完整的响应体,直到我终止服务器。身体也在被修改,但有些进入无限循环。我是节点JS的新手,因此感谢任何帮助。

var express = require('express'),
http    = require('http'),
request = require('request'),
url = require('url'),
app     = express();

function bodymodule(req,res,next){
var pathname = req.protocol+ '://'+req.get('host')+   req.originalUrl;
   console.log(pathname);
request(pathname, function (error, response, body) {
if (!error && response.statusCode == 200) {
        body = body.replace(/(<\/body>)/, "<script>alert('hi')</script>\n\n$1");
        console.log(body); 
      }
    })
  next();
  };

我的理解是,一旦我致电&#39; http://localhost:3000/login&#39;,它会再次作为新请求点击我的服务器,此过程将继续,并且我会一次又一次地获取响应正文。 如果是这样,我应该选择哪种替代方式。

我也尝试了其他方法,但没有人为我工作。请帮助

编辑1 - :

这是我想要执行的代码

var express = require('express'),
http    = require('http'),
request = require('request'),
url = require('url'),
app     = express();


function bodymodule(req,res,next){
  var pathname = req.protocol+ '://'+req.get('host')+         req.originalUrl;
console.log(pathname);
request(pathname, function (error, response, body) {
if (!error && response.statusCode == 200) {
    body = body.replace(/(<\/body>)/, "<script>alert('hi')</script>\n\n$1");
    console.log(body); 
  }
})
next();
  };

app
.use(express.static('./public'))
.use(bodymodule)
.get('*', function (req, res) {
    if (!req.user) {
        res.redirect('/index1');
        return res.send();
    } else {
        res.sendfile('public/main.html');
    }
})
.listen(3000);

index1.html

<html>
<head>
<body>
<form action="hello.html" method="GET">
<input type ="submit" value = "submit">
</form>
</body>
</head>
</html>

0 个答案:

没有答案
相关问题