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;

 

posted @ 2018-03-09 16:29  卢传奇  阅读(294)  评论(0编辑  收藏  举报