一、准备
npm install express -g
npm install express-generator -g
express express-node
会生成一个项目文件如下: 可以安装热更新 nodemon
npm install nodemon -D
修改启动命令:
"scripts": {
"start": "nodemon ./bin/www"
},
安装request:
npm install request -S
封装request请求:
在routes文件夹下创建/utils/fetch
const request = require('request');
const baseURL = '';
const fetch = {
get(url, data = {}) {
return new Promise((resolve, reject) => {
request(
{
method: 'GET',
url,
qs: data
},
(err, res, body) => {
if (res.statusCode === 200) {
resolve(res.body);
} else {
reject(err);
}
}
);
});
},
post(url, data = {}) {
return new Promise((resolve, reject) => {
request(
{
method: 'POST',
url,
form: JSON.stringify(data)
},
(err, res, body) => {
if (res.statusCode === 200) {
resolve(res.body);
} else {
reject(err);
}
}
);
});
}
};
module.exports = fetch;
请求转发
测试接口 http://localhost:3000/?a=1&b=2 接口返回以下则成功: {“status”:200,“msg”:“success”,“params”:{“a”:“1”,“b”:“2”}}
var express = require('express');
var router = express.Router();
const fetch = require('./utils/request');
router.get('/', function (req, res, next) {
fetch
.get('http://localhost:8000/test', req.query)
.then((result) => {
const data = JSON.parse(result);
console.log('response:', data);
res.json({
...data
});
})
.catch((err) => {
res.json({
err
});
});
});
router.get('/test', (req, res, next) => {
res.json({ status: 200, msg: 'success', params: req.query });
});
router.post('/post', (req, res, next) => {
res.json({ status: 200, msg: 'success', params: req.body });
});
router.get('/test/post', function (req, res, next) {
fetch
.post('http://localhost:8000/post', req.query)
.then((result) => {
const data = JSON.parse(result);
console.log('response:', data);
res.json({
...data
});
})
.catch((err) => {
res.json({
err
});
});
});
module.exports = router;
|