27 行 nodejs 实现请求转发
作为转发请求用的中间件,简单实用。比如做前后端分离开发的时候不需要后端实现 CORS 了。
js
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 + ".");