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);
}
})
滿天的星座2017-06-29 10:10:40
Node has various request libraries. There are also requests that come with it
The whole process is probably
The client requests the node server
The node server requests php and then packages the returned response data
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.
迷茫2017-06-29 10:10:40
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
PHP中文网2017-06-29 10:10:40
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,