Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前后端分离接口设置及调用 #25

Open
zhn4 opened this issue Aug 17, 2017 · 0 comments
Open

前后端分离接口设置及调用 #25

zhn4 opened this issue Aug 17, 2017 · 0 comments

Comments

@zhn4
Copy link
Owner

zhn4 commented Aug 17, 2017

后端部分

需要跨域,以express为例使用cors插件

$ npm install --save cors

连接数据库 models/connect.js

var mongoose = require('mongoose')

var db = mongoose.connect('mongodb://localhost:27017/music')
// movies可替换其他数据库名字

// 测试连接数据库是否成功
db.connection.on('error', function() {
  console.log('连接失败')
})
db.connection.on('open', function() {
  console.log('连接成功')
})

数据模型 models/music.js

var mongoose = require('mongoose')

var movieSchema = new mongoose.Schema({
  title: String,
  singer: String
})

var Music = mongoose.model('music', movieSchema)

module.exports = Music

api接口路由 routes/index.js

var express = require('express');
var router = express.Router();

var Music = require('../models/music.js')

module.exports = function(app) {
  app.get('/', function(req, res, next) {
    res.render('index', {
      title: 'Express'
    })
  })
  // 获取所有音乐数据
  app.get('/api/music', function(req, res, next) {
    Music.find({})
         .then(musics => {
           res.json(musics)
         })
         .catch(err => {
           res.json(err)
         })
  })
  // 增加数据
  app.post('/api/addMusic', function(req, res, next) {
    var music = new Music({
      title: req.body.title,
      singer: req.body.singer
    })
    music.save(function(err, doc) {
      if(err) {
        console.log('保存失败')
        console.log(err)
        res.json({
          msg: '保存失败'
        })
        return
      }
      console.log('保存成功')
      res.json({
        msg: '保存成功'
      })
    })
  })
  // 删除数据
  app.delete('/api/deleteMusic/:id', function(req, res, next) {
    Music.findOneAndRemove({
      _id: req.params.id
    })
    .then(res.json({msg: '删除成功'}))
    .catch(err => res.json(err))
  })
  // 多条件关键字搜索匹配
  app.post('/api/search', function(req, res, next) {
    Music.find().or([
      {
        title: new RegExp(req.body.key_word, 'i')
      },
      {
        singer: new RegExp(req.body.key_word, 'i')
      }
    ])
    .then(musics => {
      res.json(musics)
    })
    .catch(err => {
      res.json(err)
    })
  })
}

修改app.js

// 引入跨域模块
var cors = require('cors')
// 使用跨域模块
app.use(cors())

// 引入连接数据的js
require('./models/connect')

// 引用路由
var router = require('./routes/index')

router(app)

完整app.js配置

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var cors = require('cors')

require('./models/connect')

// var index = require('./routes/index');
// var users = require('./routes/users');
var router = require('./routes/index')

var app = express();
app.use(cors())

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// app.use('/', index);
// app.use('/users', users);
router(app)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

前端部分

前端使用React,使用Fetch发送请求

获取所有数据

  componentWillMount() {
    fetch('http://localhost:3000/api/music', {
      method: 'get',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Accept': 'application/json'
      }
    }).then(res => {
        if(res.ok) {
          console.log(res)
          res.json().then(json => {
            console.log(json)
            this.setState({
              songs: json
            })
          })
        }
      }).catch(err => {
        console.log(err)
      })

提交增加数据

  handleSubmit() {
    if(this.refs.title.value !== '' && this.refs.singer.value !== '') {
      fetch('http://localhost:3000/api/addMusic', {
        method: 'post',
        mode: 'cors',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          title: this.refs.title.value,
          singer: this.refs.singer.value
        })
      }).then(res => {
        if(res.ok) {
          res.json()
          .then(json => {
            console.log(json)
            alert(json.msg)
            // window.location.reload()
          })
        }
      }).catch(err => {
        console.log(err)
      })
    }else {
      alert('歌曲名/演唱者不能为空')
    }
  }

查询数据

  handleSearch(e) {
    if(e.key === 'Enter' && this.refs.keyword.value !== '') {
      console.log(this.refs.keyword.value)
      fetch('http://localhost:3000/api/search', {
        method: 'post',
        mode: 'cors',
        body: JSON.stringify({
          key_word: this.refs.keyword.value
        }),
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
          'Accept': 'application/json'
        },
      }).then(res => {
          if(res.ok) {
            console.log(res)
            res.json().then(json => {
              console.log(json)
              this.setState({
                songs: json
              })
            })
          }
        }).catch(err => {
          console.log(err)
        })
    }
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant