Express项目中的Ajax : Vue-cli-axios,以及文件上传

本文介绍了如何在Express项目中利用Vue-cli和Axios进行Ajax请求,包括通过npm、bower、yarn安装Axios,设置基础URL、请求头、参数、数据等,并探讨了文件上传的相关概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 npm 安装

$ npm install axios

使用bower安装

$ bower install axios

使用yarn安装

$ yarn add axios

使用cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

使用

npm包地址:https://www.npmjs.com/package/axios

//node项目中使用
const axios = require('axios');

//推荐使用下面的方法(记住这一个就够用了,更换method适应不同请求和数据发送)
//更多方法可以参照 :https://www.npmjs.com/package/axios
axios({
	method:'post',  //支持方法:get,post,put,delete,pathc,options,head 
	url:'http://localhost:3000/api/setdata',
	data:{key:value,.....}
}).then(res=>{
	console.log(res); //res为后台返回的数据
})

模板/静态页面中使用
//引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios({
	method:'post',  //支持方法:get,post,put,delete,pathc,options,head 
	url:'http://localhost:3000/api/setdata',
	data:{key:value,.....}
}).then(res=>{
	console.log(res); //res为后台返回的数据
})
<input name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="update"/>
---
import axios from 'axios'
// 添加请求头
update (e) {   // 上传照片
      var self = this
      let file = e.target.files[0]
      /* eslint-disable no-undef */
      let param = new FormData()  // 创建form对象
      param.append('file', file)  // 通过append向form对象添加数据
      param.append('chunk', '0') // 添加form表单中其他数据
      console.log(param.get('file')) // FormData私有类对象,访问不到,可以通过get判断值是否传进去
      let config = {
        headers: {'Content-Type': 'multipart/form-data'}
      }
     // 添加请求头
    axios.post('http://172.19.26.60:8081/rest/user/headurl', param, config)
        .then(response => {
          if (response.data.code === 0) {
            self.ImgUrl = response.data.data
          }
          console.log(response.data)
        })
    }

  1. url是将用于请求的服务器URL
    url: ‘/user’,

  2. method是发出请求时使用的请求方法
    method: ‘get’, // 默认

  3. baseURL将被添加到url前面,除非url是绝对的。
    // 可以方便地为 axios 的实例设置baseURL,以便将相对 URL 传递给该实例的方法。
    baseURL: ‘https://some-domain.com/api/’,

  4. transformRequest允许在请求数据发送到服务器之前对其进行更改
    // 这只适用于请求方法’PUT’,’POST’和’PATCH’
    // 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream
    transformRequest: [function (data) {
    // 做任何你想要的数据转换 然后 return data;
    }],

  5. transformResponse允许在 then / catch之前对响应数据进行更改
    transformResponse: [function (data) {
    // 做任何你想要的数据转换 然后 return data;
    }],

  6. headers是要发送的自定义 headers
    headers: {‘X-Requested-With’: ’XMLHttpRequest’},

  7. params是要与请求一起发送的URL参数
    // 必须是纯对象或URLSearchParams对象
    params: {
    ID: 12345
    },

  8. paramsSerializer是一个可选的函数,负责序列化params
    // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
    paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: ’brackets’})
    },

  9. data是要作为请求主体发送的数据
    // 仅适用于请求方法“PUT”,“POST”和“PATCH”
    // 当没有设置transformRequest时,必须是以下类型之一:
    // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
    // - Browser only: FormData, File, Blob
    // - Node only: Stream
    data: {
    firstName: ’Fred’
    },

  10. timeout指定请求超时之前的毫秒数。
    // 如果请求的时间超过’timeout’,请求将被中止。
    timeout: 1000,

  11. withCredentials指示是否跨站点访问控制请求
    withCredentials: false, // default

  12. `adapter’允许自定义处理请求,这使得测试更容易。
    // 返回一个promise并提供一个有效的响应(参见[response docs](#response-api))
    adapter: function (config) {
    /* … */
    },

  13. auth’表示应该使用 HTTP 基本认证,并提供凭据。 // 这将设置一个Authorization’头,覆盖任何现有的Authorization’自定义头,使用headers`设置。
    auth: {
    username: ’janedoe’,
    password: ’s00pers3cret’
    },

  14. “responseType”表示服务器将响应的数据类型
    // 包括 ‘arraybuffer’, ‘blob’, ‘document’, ‘json’, ‘text’, ‘stream’
    responseType: ‘json’, // default

  15. xsrfCookieName是要用作 xsrf 令牌的值的cookie的名称
    xsrfCookieName: ‘XSRF-TOKEN’, // default

  16. xsrfHeaderName是携带xsrf令牌值的http头的名称
    xsrfHeaderName: ‘X-XSRF-TOKEN’, // default

  17. onUploadProgress允许处理上传的进度事件
    onUploadProgress: function (progressEvent) {
    // 使用本地 progress 事件做任何你想要做的
    },

  18. onDownloadProgress允许处理下载的进度事件
    onDownloadProgress: function (progressEvent) {
    },

  19. maxContentLength定义允许的http响应内容的最大大小
    maxContentLength: 2000,

  20. validateStatus定义是否解析或拒绝给定的promise
    // HTTP响应状态码。如果validateStatus返回true(或被设置为null promise将被解析;否则,promise将被
    // 拒绝。
    validateStatus: function (status) {
    return status >= 200 && status < 300; // default
    },

  21. maxRedirects定义在node.js中要遵循的重定向的最大数量。
    // 如果设置为0,则不会遵循重定向。
    maxRedirects: 5, // 默认

  22. httpAgenthttpsAgent用于定义在node.js中分别执行http和https请求时使用的自定义代理。
    // 允许配置类似keepAlive的选项,
    // 默认情况下不启用。
    httpAgent: new http.Agent({ keepAlive: true }),
    httpsAgent: new https.Agent({ keepAlive: true }),

  23. ‘proxy’定义代理服务器的主机名和端口
    // auth表示HTTP Basic auth应该用于连接到代理,并提供credentials。
    // 这将设置一个Proxy-Authorization header,覆盖任何使用headers设置的现有的Proxy-Authorization 自定义 headers。

proxy: {
  host: ’127.0.0.1’,
  port: 9000,
  auth: : {
    username: ’mikeymike’,
    password: ’rapunz3l’
  }
}, 
24.  “cancelToken”指定可用于取消请求的取消令牌
cancelToken: new CancelToken(function (cancel) {
})
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Jacky张

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

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

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

打赏作者

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

抵扣说明:

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

余额充值