Ajax——axios请求

1.参考https://github.com/axios/axios

2.前端最常用的异步请求

3.代码展示

<!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>axios</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
</head>
<body>
    <button>get</button>
    <button>post</button>
    <button>axios</button>
    <script>
        const btn = document.getElementsByTagName('button')
        //配置baseURL
        axios.defaults.baseURL = 'http://127.0.0.1:8000'
        btn[0].onclick=function(){
            axios.get('/axios-server',{
                //url参数
                params:{
                    id:100,
                    vip:7
                },
                //请求头信息
                headers: {
                    name:'coco',
                    age:20
                }
                }).then(value=>{
                    console.log(value)
            })
        }
        btn[1].onclick=function(){
            axios.post('/axios-server',{
                //url参数
                params:{
                    id:200,
                    vip:9
                },
               
                //请求头信息
                headers: {
                   height:180,
                   width:200
                },
                 data:{
                    username:'admin',
                    password:'admin'

                },
                })
           
        }
        btn[2].onclick = function(){
            axios({
                url:'/axios-server',
                //url参数
                params:{
                    vip:10,
                    level:30
                },
                //头信息
                headers:{
                    a:100,
                    b:200
                },
                //请求体参数
                data:{
                    username:'admin',
                    password:'admin'
                }
            }).then(response=>{
                console.log(response)
            })
        }
    </script>
</body>
</html>

server.js

app.all('/axios-server',(request,response)=>{

    response.setHeader('Access-Control-Allow-Origin','*')
    response.setHeader('Access-Control-Allow-Headers','*')
    const data = {name:'COCO'}
    response.send(JSON.stringify(data))
})

4.请求体截图

 5.解决bug

 出现以上bug的原因是因为请求头里面有中文字体,无法编译。

只需将headers里面所有的值都改为英文即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值