m0_62693499 2022-09-21 10:52 采纳率: 100%
浏览 64
已结题

axios发送post请求问题

为什么我用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": "文学出版社"
    }
]
  • 写回答

5条回答 默认 最新

  • CSDN专家-showbo 2022-09-21 10:55
    关注
            <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阻止表单提交试试
            }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 9月29日
  • 已采纳回答 9月21日
  • 创建了问题 9月21日

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来