一般咱們經常使用的請求方法只有GET、POST、PUT和DELETE,因此在此只介紹這四種和文件上傳的代理方式javascript
在此咱們使用request.js第三方模塊實現java
GET(DELETE同GET,將request方法改成DELETE便可)api
const request = require('request'); const url = require('url'); test: function (req, res, next) { let curl = url.parse(req.url); let search= curl.search; curl = "http:/localhost:8080/api/get"+search; try { req.pipe(request({ method: 'GET', uri: curl })).pipe(res); } catch (e) { next(e); } }
POST(PUT同POST,將request方法改成put便可)curl
const request = require('request'); const url = require('url'); test: function (req, res, next) { let curl= url.parse(req.url); let search= curl.search; curl = "http://localhost:8080/api/post"+search; let body = req.body; try { request.post({ uri: curl, form: body }).pipe(res); } catch (e) { next(e); } }
代理文件上傳post
const request = require('request'); const url = require('url'); upload: function (req, res, next) { let curl= url.parse(req.url); let search= curl.search; curl = "http://localhost:8080/api/upload"+search; try { req.pipe(request({ method: 'POST', uri: curl })).pipe(res); } catch (e) { next(e); } }