关于axios的post用法

博客展示了使用axios进行POST请求的代码。设置了请求头以解决CORS头和session问题,将表单数据传递转化为form-data类型。还对响应结果进行了处理,若登录成功则3秒后跳转主页,若用户名不存在则给出提示,请求出错时弹出错误信息。
axios.post('', {
    data: params
},{
    headers: {
        'Access-Control-Allow-Origin':'*',  //解决cors头问题
        'Access-Control-Allow-Credentials':'true', //解决session问题
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //将表单数据传递转化为form-data类型
    },
    withCredentials : true
})
    .then(function (response) {
        var res = response.data;
        if(res=="登录成功,3秒后跳转主页") {
            var noticeId= JSON.parse(window.sessionStorage.getItem('user'));
            alert(noticeId)
            alert(response.data);
            setTimeout(that.LoginSuccess, 3000)
        }else if(response.data=="用户名不存在,请注册后重新登录") {
            that.message = response.data
        }
    })
    .catch(function (error) {
        alert(error);
    });
Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 Node.js。Axios 的 `post` 方法用于向服务器发送 POST 请求,通常用于提交数据。 ### 使用方法 Axios 的 `post` 方法有三个参数: - `url`:请求的 URL。 - `data`:要发送的数据,可以是对象、表单数据等。 - `config`:可选的配置对象,包含请求头、超时时间等配置信息。 ### 示例代码 以下是一些不同场景下使用 Axios `post` 方法的示例: #### 基本的 POST 请求 ```javascript const axios = require('axios'); // 要发送的数据 const data = { username: 'exampleUser', password: 'examplePassword' }; // 发送 POST 请求 axios.post('https://example.com/api/login', data) .then(response => { console.log('Response:', response.data); }) .catch(error => { console.error('Error:', error); }); ``` #### 带请求头的 POST 请求 ```javascript const axios = require('axios'); const data = { title: 'New Post', body: 'This is the body of the new post.' }; const config = { headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_token_here' } }; axios.post('https://example.com/api/posts', data, config) .then(response => { console.log('Response:', response.data); }) .catch(error => { console.error('Error:', error); }); ``` #### 在浏览器中使用 Axios 发送 POST 请求 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Axios POST Example</title> <!-- 引入 Axios --> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> </head> <body> <button id="sendPost">Send POST Request</button> <script> const button = document.getElementById('sendPost'); button.addEventListener('click', () => { const data = { message: 'Hello from the browser!' }; axios.post('https://example.com/api/message', data) .then(response => { console.log('Response:', response.data); }) .catch(error => { console.error('Error:', error); }); }); </script> </body> </html> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luolvzhou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值