axios发送post请求问题

为什么我用axios点击按钮发送POST请求,会刷新整个页面?Post请求返回的信息,在控制台打印,闪一下就没了,我尝试将button标签的type属性改成button也还是会刷新页面
html页面

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>Documenttitle>
    <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": "文学出版社"
    }
]
        <button id="btn" type="submit">点我获取</button>
改为
        <button id="btn" type="button">点我获取</button>

要不submit会提交表单,不过看题主注册的onclick事件已经e.preventDefault应该不会提交表单才对,确认是这些代码?测试了正常不会提交表单的,题主用的什么浏览器?


        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)
            })
            return false;////////////这里同时return false阻止表单提交试试
        }

在函数最后那里加上 return false;就会阻止刷新了

试着设置完整再看看呢

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632