node 后端代理服务器

无人久伴 提交于 2020-02-05 02:42:08

node 后端代理服务器

通过一个.js文件创建的服务器向另一个js文件创建的服务器发送请求数据.

server1.js

var http = require('http');
var app = http.createServer(function(req,res)
{
    if(req.url === '/')
    {
        http.get('http://localhost:8000/test',function(data)
        {
            var str = '';
            data.on('data',function(clumh)
            {
                str += clumh;
            });
            data.on('end',function()
            {
                res.end(str);
            });
        })
    }
});

app.listen(3000,function()
{
    console.log('server1 is ok');
});

server2.js

var http = require('http');
var app = http.createServer(function(req,res)
{
    if(req.url == '/test')
    {
        res.end('success!');
    }
});

app.listen(8000,function()
{
    console.log('server2 is ok');
});

将两个文件的终端都进行启动,再在页面输入http://localhost:3000/,就可以通过3000端口页面访问8000端口的页面内容了.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!