代码:
<template>
<div>
<input v-model.trim="duixiang1.username"/>
<input v-model.trim="duixiang1.password"/>
<button @click="login">登录</button>
</div>
</template>
<script>
import axios from 'axios'
export default
{
data () {
return {
duixiang1: { username: '1', password: '1' }
}
},
methods: {
login () {
if (this.duixiang1.username.length <= 0 || this.duixiang1.password.length <= 0) {
alert('注册失败!')
} else if (this.duixiang1.username === this.duixiang1.password) {
alert('账号和密码不能一样!')
} else {
this.userLogin()
}
},
userLogin () {
const data = {
username: this.duixiang1.username,
password: this.duixiang1.password
}
axios({
url: '/api/login',
method: 'post',
data
}).then(res => {
if (res.status !== 200) {
alert('注册失败!')
} else {
alert('注册成功!')
}
})
console.log(this.duixiang1.username)
}
},
created () {
}
}
</script>
后端代码:
const express=require('express')
const bodyParser=require('body-parser')
const jwt=require('jsonwebtoken')
// 因为
const app=express()
const login=require('./index')
app.use((req,res,next)=>{
res.setHeader('Access-Control-Allow-Origin','*')
next()
})
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// body
app.post('/login',(req,res)=>{
// 编写post请求
let data ={}
data=req.body
let sql=`insert into userid set username=${JSON.stringify(data.username)},password=${JSON.stringify(data.password)}`
login(sql,(err,res1)=>{
const token=jwt.sign(data,'xiaoyu',{expiresIn:'10s'})
if(err)
{
res.send({status:404,message:'error'})
}
else
{
res.send({status:200,message:'OK',token})
// 成功返回token信息
}
})
})
app.listen(3009,()=>{
console.log('服务启动了')
})
数据库部分代码:
function mysql(x1,x2)
{
const mysql=require('mysql')
const coon=mysql.createConnection({
host:'localhost',
user:'root',
password:'newpassword',
database:'mybook'
})
coon.connect
coon.query(x1,x2,(err,res)=>{
if(err)throw err
console.log(res)
})
}
module.exports=mysql
好了以上就是简单新手代码,post请求代码!
聪明的你应该知道怎么做了吧!