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 });//將服務(wù)器代理到localhost:8080端口上[本地服務(wù)器為localhost:3000]
app.use('*', apiProxy);//子目錄下的都是用代理
app.get('/index', function(req,res){
//我想在這里匹配到路由,然后在這里發(fā)送請(qǐng)求拿數(shù)據(jù)
//然后根據(jù)返回的數(shù)據(jù)傳送到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);
}
})
業(yè)精于勤,荒于嬉;行成于思,毀于隨。
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.
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
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,