之前做的从数据库中读取数据渲染到页面上的操作称为后端渲染。采用后台接口的方式,后台只提供数据,所有与页面有关的操作都放在前端来做,这种开发模式是前后端分离的,称作前端渲染。
几个主流的后台接口开发
1.json接口
2.jsonp接口(跨域接口)
3.restful接口
下面简单演示一下这三个接口的方式:
/**
* 后台接口开发
*/
const express = require('express');
const db = require('./db.js');
const app = express();
//指定api路径 allBooks(json接口)
app.get('/allBooks',(req,res) => {
let sql = 'select * from book';
db.base(sql,null,(result) => {
res.json(result);
});
});
//默认的回调函数的名称就是callback,如果想要覆盖默认的名称,执行下面语句即可
//默认的访问方式为:http://localhost:3000/allBooks?callback=foo
//访问方式为:http://localhost:3000/allBooks?cb=foo
//如果访问错误,浏览器不会报错,而是返回json格式的数据
app.set('jsonp callback name','cb');
//指定api路径 allBooks(jsonp接口)
app.get('/allBooks',(req,res) => {
let sql = 'select * from book';
db.base(sql,null,(result) => {
res.jsonp(result);
});
});
app.listen(3000,()=>{
console.log('running...');
});
/**
* restful api 是从URL的格式来表述的
* get http://localhost:3000/books
* get http://localhost:3000/books/book
* post http://localhost:3000/books/book
* get http://localhost:3000/books/book/1
* put http://localhost:3000/books/book
* delete http://localhost:3000/books/book/2
*
* 传统的URL风格:
* http://localhost:3000/
* http://localhost:3000/toAddBook
* http://localhost:3000/addBook
* http://localhost:3000/toEditBook?id=1
* http://localhost:3000/editBook
* http://localhost:3000/deleteBook?id=2
*/
const express = require('express');
const db = require('./db.js');
const app = express();
app.get('/books',(req,res)=>{
let sql = 'select * from book';
db.base(sql,null,(result) => {
res.json(result);
});
});
//如果你的路由为'/books/book/:id',id属性就可以以req.params.id形式获取到
app.get('/books/book/:id',(req,res) => {
let id = req.params.id;
let sql = 'select * from book where id=?';
let data = [id];
db.base(sql,data,(result) => {
res.json(result[0]);
});
});
app.listen(3000,()=>{
console.log('running...');
});