javascript - How node requests other servers.
迷茫
迷茫 2017-06-29 10:08:40
0
4
843

The project wants to use node as the middle layer.
The first layer browser sends a request to node
The second layer node sends a request to php
I know a little bit about the node and express framework. How does node send a request? Is there a simple and easy way to get the data in php and return it to the front desk?

Using http-proxy-middleware I can get the data, but I want to match the route and then send the request to the background to render the ejs template.

const apiProxy = proxy('/do', { target: 'http://wx.lxjjz.cn',changeOrigin: true });//将服务器代理到localhost:8080端口上[本地服务器为localhost:3000]
app.use('*', apiProxy);//子目录下的都是用代理
 
app.get('/index', function(req,res){
     //我想在这里匹配到路由,然后在这里发送请求拿数据
     //然后根据返回的数据传送到ejs模版渲染
     res.sendFile(__dirname+'/index.html');
});
 

Client

var contextPath = 'http://wx.lxjjz.cn';
                $.ajax({
                    type:'get',
                    url:contextPath+'/do?g=api&m=hd&a=works-list',
                    success:function(data){
                        console.log(data);
                    },
                    error:function(data){
                        console.log(data);
                    }
 
                })
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(4)
滿天的星座

Node has various request libraries. There are also requests that come with it

The whole process is probably

  1. The client requests the node server

  2. The node server requests php and then packages the returned response data

  3. Return the above packaged data to the client

What you need to pay attention to is to handle the callback. If you want to look better, you can use promise or co module to handle asynchronous code.

迷茫

There are various solutions to this, let me just talk about the one we use node-rest-client
For example, if you use express, write a route yourself, if /ajax is used to accept front-end requests
front-end requests are sent to / Ajax is enough, and then in /ajax, use node-rest-client to forward the request to php. After php returns the data, res.json(data) is enough. Of course, you need to encapsulate and unify the data yourself during this process. These are all small things, the main idea is probably like this

刘奇

http-proxy-middleware

Ty80

If it is just forwarding by proxy,

If the middle layer does not encapsulate any data, you can use this middleware:

https://github.com/chimurai/h...

Normally speaking, nodes are used for data encapsulation. The API layer does not care about business, so it can be decoupled.

Then you need to make various interfaces separately, get the data, reorganize it yourself using lodash and moment, and send it to the front desk,

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template