node中間層

  • 用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();
  }
});

 

  • axios請求數據,轉發前端
  1. npm install axios --save
  2. 書寫代碼
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;
相關文章
相關標籤/搜索