- 用express脚手架生成项目结构
- node跨域设置
app.all('*',function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (req.method == 'OPTIONS') {
res.send(200); /让options请求快速返回/
}
else {
next();
}
});
- npm install axios --save
- 书写代码
var express = require('express');
var axios = require('axios')
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
axios.get('https://api.douban.com/v2/book/1220562').then(response => {
console.log(response.data)
// res.render('index',{title: JSON.stringify(response.data)});
res.json(response.data);
}).then(err => {
console.log(err)
})
});
router.get('/first', function(req, res, next) {
axios.get('https://api.douban.com/v2/book/1220561').then(response => {
res.json(response.data);
}).catch(err => {
console.log(err)
})
});
module.exports = router;