【无标题】

后端:

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'
        }
      })

//问题是 我每次写入留言要重启服务器才可以再次渲染到前端页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值