为什么我用axios点击按钮发送POST请求,会刷新整个页面?Post请求返回的信息,在控制台打印,闪一下就没了,我尝试将button标签的type属性改成button也还是会刷新页面
html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 1000px;
border: 1px solid orange;
}
</style>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<form action="##">
<input type="text" id ="bookname"placeholder="书名">
<input type="text" id ="author"placeholder="作者">
<input type="text" id ="publisher"placeholder="出版社">
<button id="btn" type="submit">点我获取</button>
</form>
<div></div>
<script>
function getData() {
axios({
method: 'get',
url: 'http://127.0.0.1:8080/sb'
}).then(data => {
console.log('get的返回数据',data)
const arr = data.data.data
arr.forEach(item => {
const divNew = document.createElement('div')
divNew.innerHTML = `${item.id}--${item.bookname}--${item.author}--${item.publisher}`;
document.querySelector('div').appendChild(divNew)
})
})
}
getData()
document.getElementById('btn').onclick = function (e) {
e.preventDefault()
const bookname = document.getElementById('bookname').value.trim()
const author = document.getElementById('author').value.trim()
const publisher = document.getElementById('publisher').value.trim()
axios({
method: 'post',
url: 'http://127.0.0.1:8080/add',
data:{
bookname,
author,
publisher
}
}).then(data=>{
console.log('post返回的数据',data)
})
}
</script>
</body>
</html>
服务器
const { query, add } = require('./tools.js')
const cors = require('cors')
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
app.use(cors())
app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.get('/sb', async (req, res) => {
const arr = await query()
res.send({
status: 200,
msg: '成功',
data: arr
})
})
app.post('/add', async (req, res) => {
const arr = await add(req.body)
res.send({ status: 201, msg: '成功' })
})
app.listen(8080, () => {
console.log('服务器运行了,端口号是8080')
})
读取数据
const { join } = require('path');
const { readFile, writeFile } = require('then-fs');
const filename = join(__dirname, 'db.json')
async function query() {
const res = await readFile(filename, 'utf-8');
return JSON.parse(res)
}
async function add(obj) {
const res = await query()
obj.id = res[res.length-1].id + 1
res.push(obj)
return writeFile(filename, JSON.stringify(res))
}
//const res = add({ bookname: '《三国演义》', author: '罗贯中', publisher: '人民邮电出版社' })
module.exports={
query,
add
}
后台数据
[
{
"id": 1,
"bookname": "《朝花夕拾》",
"author": "鲁迅",
"publisher": "文学出版社"
}
]