avatar
fireworks99
keep hungry keep foolish

FrontEnd Vue pass info to BackEnd Nodejs

Description

前端用Vue框架写一个“注册”页面,需要传递一些注册信息到后端Nodejs,以便写入MySQL完成注册。

<input type="text"
                     name="usernm"
                     required="required"
                     class="border-item"
                     placeholder="username"
                     value=""
                     v-model="username">
<input type="password"
                     name="passwd"
                     required="required"
                     class="border-item"
                     placeholder="password"
                     value=""
                     v-model="password">

v-model实现前后端的双向绑定

而v-bind只是后端向前端的单向绑定

<input type="submit"
                     name="submit"
                     value="Submit"
                     class="btn"
                     @click="getRegister">

点击submit按钮触发getRegister()函数

import axios from 'axios'

export function request(config) {

  // 1 创建实例
  const instance = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 5000,
    // headers: {
    //   'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    // },
  });

  // 2 两类拦截器
  instance.interceptors.request.use(config => {
    return config
  }, error => {
    console.log(error);
  });

  instance.interceptors.response.use(res => {
    return res.data
  }, error => {
    console.log(error);
  });

  //3 发送真正的网络请求
  return instance(config)
}

上述为封装好的网络请求(后端NodeJS设置允许跨域访问,运行在3000端口)

import {request} from "./request";

export function getRegister(username, password) {
  return request({
    url: '/register_process',
    params: {
      username,
      password
    }
  })
}

export function getLogin(username, password) {
  return request({
    url: '/login_process',
    params: {
      username,
      password
    }
  })
}

上述为封装好的getRegister请求,getRegister被调用后发出请求localhost:3000/register_process,后端NodeJS收到请求,进行处理

const connection = require("./connect.js")

module.exports = function (username, password) {

  connection.query('use blogs', function (err, res) {
    if(err) throw err;
    console.log("Succeed : " + res);
  })

  const sql = 'insert into users(username, password) values("' + username + '", "' + password + '")'

  connection.query(sql, function (err, res) {
        if(err) {
          // callback(err);
          throw err;
        }
        console.log("Succeed : " + res);
      })
  // callback('Succeed')
}

上述为封装好的register.js将数据写入MySQL数据库

const register = require('./db/register')
router.get('/register_process', function (req, res) {
  // console.log(req.query.username);
  // console.log(req.query.password);
  register(req.query.username, req.query.password)
})

express的router处理请求:调用register.js完成数据入库

Site by Baole Zhao | Powered by Hexo | theme PreciousJoy