## 一、通过request模块转接口
安装模块(https://www.npmjs.com/package/request)
~~~
npm install --save request
~~~
GET
~~~
var request = require('request');
request('http://www.baidu.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the baidu homepage.
}
})
~~~
POST(**application/json**)
~~~
request({
url: url,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body: JSON.stringify(requestData)
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
}
})
~~~
POST(**application/x-www-form-urlencoded**)
~~~
request.post({url:'http://service.com/upload', form:{key:'value'}}, function(error, response, body) {
if (!error && response.statusCode == 200) {
}
})
~~~
POST(**multipart/form-data**)
~~~
var formData = {
// Pass a simple key-value pair
my_field: 'my_value',
// Pass data via Buffers
my_buffer: new Buffer([1, 2, 3]),
// Pass data via Streams
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
};
request.post({url:'http://service.com/upload', formData: formData}, function (error, response, body) {
if (!error && response.statusCode == 200) {
}
})
~~~
在路由中使用 api/index.js
~~~
var express = require('express');
var router = express.Router();
var request = require('request');
// 获取列表
router.post('/list', function(req, res, next) {
request({
url: 'http://www.xxx.com/list',
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body: JSON.stringify(requestData)
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
res.send(body);
}
});
});
~~~
参考链接:
https://blog.csdn.net/dreamer2020/article/details/52074516