1、跨域的问题,需要安装跨域模块
npm install cors
2、app.js导入跨域模块
var cors = require('cors');
app.use(cors());
3、对数据库进行链接配置
新建dbconfig.js文件
const Sequelize = require('sequelize');
const MysqlDB = new Sequelize('dbms','root','178945688',{
host: 'localhost',
port: 3306,
dialect: 'mysql',
pool: {
max: 20,
min: 3,
idle: 10000
}
})
module.exports = MysqlDB;
4、建立模型
//创建bookModel.js
const Sequelize = require('sequelize');
const MysqlDB = require('../config/dbconfig');
const Book = MysqlDB.define('bookInfo',{
id: {
type: Sequelize.INTEGER,
autoIncrement: true, //是不是自增
primaryKey: true //是不是主键
},
isbn:{
type: Sequelize.CHAR(13),
allowNull: false,
unique: true
},
name: {
type: Sequelize.STRING(200),
allowNull: false,
unique: true //表示取值唯一
},
author: {
type: Sequelize.STRING(100),
allowNull: false
},
press: {
type: Sequelize.STRING(100),
allowNull: false
},
price: {
type: Sequelize.DECIMAL(7,2),
allowNull: false
},
pubdate: {
type: Sequelize.DATE,
allowNull: false
},
imgpath: {
type: Sequelize.STRING(255),
allowNull: false
}
},
{
freezeTableName: true,
timestamps: false
})
module.exports = Book;
5、新建一个接口文件
//创建bookApi.js
var express = require('express');
var router = express.Router();
const Book = require('../../model/bookModel');
/*
* http://localhost:8089/bookapi/books
**/
router.get('/books',(req, res) => {
Book.findAll({
raw: true
}).then(result=>{
res.json(result)
}).catch(err=>{
console.log(err)
})
})
module.exports = router;
6、创建组件
import React,{ Component } from 'react'
import { Table,Button,Glyphicon } from "react-bootstrap";
import './home.css'
import { HOST,PORT } from "../config/apiconfig";
import axios from "axios";
class UserTable extends Component{
constructor(props) {
super(props);
this.state = {
data: []
}
}
componentDidMount() {
const _this = this;
axios.get(`${HOST}:${PORT}/bookapi/books`)
.then((res)=>{
_this.setState({
data: res.data //data对应的是后台封装的result
})
}).catch(err=>{
console.log(err)
})
}
render() {
const { data } = this.state
return (
<div>
<Table bordered striped hover>
<thead>
<tr>
<th width={100}>编号</th>
<th width={100}>ISBN</th>
<th width={200}>书名</th>
<th width={100}>作者</th>
<th width={100}>出版社</th>
<th width={100}>单价</th>
<th width={200}>出版时间</th>
<th width={100}>封面</th>
<th width={200} colSpan={2}>操作</th>
</tr>
</thead>
<tbody>
{
data.map((book)=>{
return (
<tr key={book.id}>
<td>{ book.id }</td>
<td>{ book.isbn }</td>
<td>{ book.name}</td>
<td>{ book.author}</td>
<td>{ book.press}</td>
<td>{ book.price}</td>
<td>{ book.pubdate}</td>
<td>{ book.imgpath}</td>
<td>
<Button bsStyle='link' bsSize='small'>
<Glyphicon glyph='edit'/>
编辑
</Button>
</td>
<td>
<Button bsStyle='link' bsSize='small'>
<Glyphicon glyph='remove'/>
删除
</Button>
</td>
</tr>
)
})
}
</tbody>
</Table>
</div>
)
}
}
//导出组件
export default UserTable;
7、修改App.js
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<UserTable />
</header>
</div>
);
}
export default App;
|