前言

axios是什么?


Axios是通过Promise实现XHR封装,其中Promise是控制手段,XHR是实际发送Http请求的客户端。都是AJAX技术的一种具体实现。


因为vue的火爆让axios成为现在比较流行的异步请求方式。本文章只是针对新手,大佬可以跳过。


一、常用写法

1.第一种

代码如下(示例(get方式))


// get传参数        后端接收   req.query 
axios.get('请求地址', { 
    //参数/
    params: {
      ID: 12345
    }
 
}) .then(function (response) { console.log(response); }) 
.catch(function (error) { console.log(error); });
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

axios.get是get请求方式 ,params是参数属性里面写字段名:this.当前组件变量。then是成功后的回调函数,catch错误后的回调函数。


2.第二种

代码如下(示例(post方式))


//post传参
axios.post('/url',{
 
  firstName: 'Fred',        // 参数 firstName
    lastName: 'Flintstone'    // 参数 lastName
 
}).then(res=>{
console.log(res);
}).catch(err=>{
 
console.log(err);
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

二、向后台上传文件(图片)

代码如下(示例):


html代码:


<input type="file"  v-on:change="update" nullmsg="新闻图片不能为空">
  • 1.

js代码:


param.append('files', file)向formData对象添加数据时候一定要注意:files是对应后台的参数名要不然传不过去的

update (e) {  // 上传照片
 
 
   let file = e.target.files[0]
   console.log({data:file})
  
   let param = new FormData() // 创建form对象
//注意files是对应后台的参数名哦   
param.append('files', file) // 通过append向form对象添加数据 
       //console.log(param);                                 // 添加form表单中其他数据
   console.log(param.get('files')) // FormData私有类对象,访问不到,可以通过get判断值是否传进去
 
   // 添加请求头
  axios.post('/admin/FileSave',param,{
                'Content-type' : 'multipart/form-data'
            })
    .then(response => {
        console.log(response.data)
     if (response.data.code === 0) {
       console.log(response.data)
     
     }
    
    })
  }
  //图片
 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.

核心代码:

前端:


<form>
  <input type="file" id="fileInput">
  <button type="submit">Upload</button>
</form>
 
<script>
  const form = document.querySelector('form');
  const fileInput = document.querySelector('#fileInput');
 
  form.addEventListener('submit', event => {
    event.preventDefault();
 
    const formData = new FormData();
    formData.append('file', fileInput.files[0]);
 
    fetch('/api/upload', {
      method: 'POST',
      body: formData
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));
  });
</script>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

后端代码(C#):


[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
    if (file == null || file.Length == 0)
    {
        return BadRequest("No file selected.");
    }
 
    var fileName = Path.GetFileName(file.FileName);
    var filePath = Path.Combine("wwwroot", fileName);
 
    using (var stream = new FileStream(filePath, FileMode.Create))
    {
        await file.CopyToAsync(stream);
    }
 
    return Ok("File uploaded successfully.");
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

总结

axios是十分方便的Http库,大家写的时候注意符号这些,用起来都是很快的。