Node.js/nuxt/axios

来自康健生活
Kangkk​(留言 | 贡献)2020年8月4日 (二) 07:52的版本 (→引言)

引言

复杂数据格式

post 请求中常见的 content-type 的值有四种

  • application/x-www-form-urlencoded 表单提交的数据类型
  • multipart/form-data 文件上传时要使用的数据类型
  • application/json json 格式的数据类型(默认类型)
  • text/xml
Warning: axios 默认的数据类型为 application/json,如果后端不能接受到 post 的请求的信息体,就是因为不能正确识别 json 请求

封装

@nuxtjs/axios

nuxt 自带 @nuxtjs/axios,不需单独安装 axios。

在页面组件中引用时,在 mounted 中有效,在 methods 中无效。

<script>
    export default {
        name: "ly-footer",
...
        mounted() {
            this.$axios.get.....;
        },
        methods: {
...
        },
    }
</script>

需要注意的是 @nuxtjs/axios 不支持 axios.all 方法。(使用 Promise.all 代替)

// In asyncData or fetch

// Parallel requests
const [ foo, bar] = await Promise.all([getFoo(), getBar()])

// Sequential requests
const foo= await getFoo()
const bar= await getBar()

模板:Leftrightflex

或者自己封装

// Expose all/spread
axios.all = function all(promises) {
  return Promise.all(promises);
};

// Axios.speard
module.exports = function spread(callback) {
  return function wrap(arr) {
    return callback.apply(null, arr);
  }
};