后端:
const express = require('express');
const mysql = require('mysql');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser')
// const jwt = require('jsonwebtoken')
//接受请求体内部json,urlencoded数据
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
//引入外部模板
const User = require("./models/user")
const UserMessage = require("./models/userMessage")
//密钥
process.env.SECRET_KEY = 'secret'
//使用cors 解决跨域问题
app.use(cors());
//1.连接数据库
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'yyzszka1103',
database: 'nba'
});
db.connect();
//words
let words = []
db.query("select* from words", function (err, res) {
if (err) throw err;
for (let i in res) {
words[i] = res[i]
}
app.get('/words', (req, res) => {
res.send(words);
})
})
//留言
app.post('/write', (req, res) => {
// console.log(req.body)
const userData = {
name: req.body.name,
text: req.body.text,
date: req.body.date
}
//存
UserMessage.create(userData)
.then((user) => {
res.json({status: user.text + " 写入成功"})
})
.catch((err) => {
res.send("error" + err)
})
})
//关闭连接
db.end();
app.listen(3000, () => {
console.log('success')
});
前端:
//这里是得到数据
axios.get('http://localhost:3000/words/')
.then(res => {
this.arr = res.data
console.log(res)
})
//这里是写留言
axios({
url: 'http://localhost:3000/write/',
method: "post",
data: {
name: this.name,
text: this.text,
date: this.time
},
transformRequest: [function (data) {
// Do whatever you want to transform the data
let ret = ''
for (let it in data) {
// 如果要发送中文 编码
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
//问题是 我每次写入留言要重启服务器才可以再次渲染到前端页面