美文网首页
接口问题

接口问题

作者: sweetBoy_9126 | 来源:发表于2019-06-01 21:25 被阅读0次
    1. v2/order/address/def/{id}.json
      对于上面这种接口,你需要改成
      v2/order/address/def/:id.json
      意思就是把id作为一个变量放进去
    {
        name: 'setDefaultAddress',
        method: 'POST',
        desc: '设置默认收货地址',
        path: 'v2/order/address/def/:id.json',
        mockPath: '',
        params: {
          id: '',
          token: '',
          ext1: 10
        }
      },
    
    1. 接口传递form-data格式的参数
      在接口的header里添加
    export function saveItemImage(params) {
      return request({
        url: '/haitao/saveItemImage',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        method: 'post',
        data: params
      })
    }
    

    然后传递的参数作为url的查询参数形式传递(比如参数字段是id和itemFile)

    const data = 'id=' + this.ids + '&itemFile=' + this.dialogImageUrl)
    saveItemImage(data).then(
            response => {
              console.log(response)
            }
          )
    
    1. 如果要把参数放到url必须用params,如果要把参数放到body里必须用data
    export function selectOrderInfoList(data) {
      return request({
        url: '/order/selectOrderInfoList',
        method: 'post',
        headers: {
          'Content-Type': 'application/json'
        },
        // 参数放到请求体中
        data
      })
    }
    
    
    export function confirmPrize(params) {
      return request({
        url: '/weibo/v2/confirmPrize',
        method: 'post',
        // 参数放到url重
        params
      })
    }
    
    

    一部分放到url中一部分放到body中(get只能把参数放在url里,不能放到body里,post既可以放到url又可以放到body)

    export function getList(params, data) {
      return request({
        url: '/weibo/v2/pageView/getList',
        method: 'post',
        params,
        data
      })
    }
    getPageView() {
            getList({ pageNum: this.pageNum, currentPage: this.currentPage }, { title: this.title, status: this.status })
              .then(
                res => {
                  this.tableData = res.dataList
                  this.totalSize = res.totalSize
                }
              )
          }
    
    
    image
    1. axios

    请求配置

    这些是用于发出请求的可用配置选项。 只有url是必需的。 如果未指定方法,请求将默认为GET。

    {
      // `url`是将用于请求的服务器URL
      url: '/user',
    
      // `method`是发出请求时使用的请求方法
      method: 'get', // 默认
    
      // `baseURL`将被添加到`url`前面,除非`url`是绝对的。
      // 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。
      baseURL: 'https://some-domain.com/api/',
    
      // `transformRequest`允许在请求数据发送到服务器之前对其进行更改
      // 这只适用于请求方法'PUT','POST'和'PATCH'
      // 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream
      transformRequest: [function (data) {
        // 做任何你想要的数据转换
        return data;
      }],
    
      // `transformResponse`允许在 then / catch之前对响应数据进行更改
      transformResponse: [function (data) {
        // Do whatever you want to transform the data
        return data;
      }],
    
      // `headers`是要发送的自定义 headers
      headers: {'X-Requested-With': 'XMLHttpRequest'},
    
      // `params`是要与请求一起发送的URL参数
      // 必须是纯对象或URLSearchParams对象
      params: {
        ID: 12345
      },
    
      // `paramsSerializer`是一个可选的函数,负责序列化`params`
      paramsSerializer: function(params) {
        return Qs.stringify(params, {arrayFormat: 'brackets'})
      },
    
      // `data`是要作为请求主体发送的数据(如果将headers修改为json格式不起作用,那么就需要把params改为data)
      // 仅适用于请求方法“PUT”,“POST”和“PATCH”
      // 当没有设置`transformRequest`时,必须是以下类型之一:
      // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
      // - Browser only: FormData, File, Blob
      // - Node only: Stream
      data: {
        firstName: 'Fred'
      },
    
      // `timeout`指定请求超时之前的毫秒数。
      // 如果请求的时间超过'timeout',请求将被中止。
      timeout: 1000,
    
      // `withCredentials`指示是否跨站点访问控制请求
      // should be made using credentials
      withCredentials: false, // default
    
      // `adapter'允许自定义处理请求,这使得测试更容易。
      // 返回一个promise并提供一个有效的响应(参见[response docs](#response-api))
      adapter: function (config) {
        /* ... */
      },
    
      // `auth'表示应该使用 HTTP 基本认证,并提供凭据。
      // 这将设置一个`Authorization'头,覆盖任何现有的`Authorization'自定义头,使用`headers`设置。
      auth: {
        username: 'janedoe',
        password: 's00pers3cret'
      },
    
      // “responseType”表示服务器将响应的数据类型
      // 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
      responseType: 'json', // default
    
      //`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称
      xsrfCookieName: 'XSRF-TOKEN', // default
    
      // `xsrfHeaderName`是携带xsrf令牌值的http头的名称
      xsrfHeaderName: 'X-XSRF-TOKEN', // default
    
      // `onUploadProgress`允许处理上传的进度事件
      onUploadProgress: function (progressEvent) {
        // 使用本地 progress 事件做任何你想要做的
      },
    
      // `onDownloadProgress`允许处理下载的进度事件
      onDownloadProgress: function (progressEvent) {
        // Do whatever you want with the native progress event
      },
    
      // `maxContentLength`定义允许的http响应内容的最大大小
      maxContentLength: 2000,
      // `validateStatus`定义是否解析或拒绝给定的promise
      // HTTP响应状态码。如果`validateStatus`返回`true`(或被设置为`null` promise将被解析;否则,promise将被
      // 拒绝。
      validateStatus: function (status) {
        return status >= 200 && status < 300; // default
      },
    
      // `maxRedirects`定义在node.js中要遵循的重定向的最大数量。
      // 如果设置为0,则不会遵循重定向。
      maxRedirects: 5, // 默认
    
      // `httpAgent`和`httpsAgent`用于定义在node.js中分别执行http和https请求时使用的自定义代理。
      // 允许配置类似`keepAlive`的选项,
      // 默认情况下不启用。
      httpAgent: new http.Agent({ keepAlive: true }),
      httpsAgent: new https.Agent({ keepAlive: true }),
    
      // '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'
        }
      },
    
      // “cancelToken”指定可用于取消请求的取消令牌
      // (see Cancellation section below for details)
      cancelToken: new CancelToken(function (cancel) {
      })
    }
    
    
    var instance = axios.create({
    baseURL: '[https://some-domain.com/api/'](https://links.jianshu.com/go?to=https%3A%2F%2Fsome-domain.com%2Fapi%2F%27),
    timeout: 1000,
    headers: {'X-Custom-Header': 'foobar'}
    });
    //等价于
    axios({
    baseURL: '[https://some-domain.com/api/'](https://links.jianshu.com/go?to=https%3A%2F%2Fsome-domain.com%2Fapi%2F%27),
    timeout: 1000,
    headers: {'X-Custom-Header': 'foobar'}
    })
    

    使用 then 时,您将收到如下响应:

    axios.get('/user/12345')
      .then(function(response) {
        console.log(response.data);
        console.log(response.status);
        console.log(response.statusText);
        console.log(response.headers);
        console.log(response.config);
      });
    

    文件上传二进制流文件类型
    1). 将 Content-type 改为:multipart/form-data
    2). 参数通过formData形式传

          const formData = new FormData()
          // 将文件转为二进制流
          formData.append('file', file)
          formData.append('group_id', queryRef.current.group_id)
          formData.append('file_name', file.name)
          dispatch({
            type: 'spider/uploadTemplate',
            payload: formData,
            callback: res => {
              const { code, data = {}, msg = '上传失败' } = res || {}
              if (code === 0) {
                message.success('文件上传成功')
              } else {
                message.error(msg)
              }
            }
          })
    

    相关文章

      网友评论

          本文标题:接口问题

          本文链接:https://www.haomeiwen.com/subject/yecztctx.html