{ const pathname = url.parse(re ...">

27 行 nodejs 实现请求转发

作为转发请求用的中间件,简单实用。比如做前后端分离开发的时候不需要后端实现 CORS 了。

const http = require("http");
const url = require("url");
http
  .createServer((request, response) => {
    const pathname = url.parse(request.url).pathname;
    let content = "";
    const opt = { host: "target_host", port: "80", method: "GET", path: pathname };
    const req = http
      .request(opt, res => {
        res
          .on("data", body => {
            console.log("return");
            content += body;
          })
          .on("end", () => {
            response.writeHead(200, { "Content-Type": "text/html" });
            response.write(content);
            response.end();
          });
      })
      .on("error", e => {
        console.log("Got error: " + e.message);
      });
    req.end();
  })
  .listen(80);
console.log("Server runing at port: " + 80 + ".");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27