Node.js/nuxt/axios:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|”
标签:ReplaceText 移动版编辑 移动版网页编辑
 
(未显示同一用户的6个中间版本)
第1行: 第1行:
== 引言 ==
== 引言 ==
== 复杂数据格式 ==
post 请求中常见的 content-type 的值有四种
* application/x-www-form-urlencoded 表单提交的数据类型
* multipart/form-data 文件上传时要使用的数据类型
* application/json json 格式的数据类型(默认类型)
* text/xml
{{Warning|axios 默认的数据类型为 application/json,如果后端不能接受到 post 的请求的信息体,就是因为不能正确识别 json 请求}}
== 使用方式 ==
=== Component ===
==== asyncData ====
<syntaxhighlight lang="javascript">
async asyncData({ $axios }) {
  const ip = await $axios.$get('http://icanhazip.com')
  return { ip }
}</syntaxhighlight>
==== methods/created/mounted ====
<syntaxhighlight lang="javascript">
methods: {
  async fetchSomething() {
    const ip = await this.$axios.$get('http://icanhazip.com')
    this.ip = ip
  }
}</syntaxhighlight>
=== Store ===
==== nuxtServerInit ====
<syntaxhighlight lang="javascript">
async nuxtServerInit ({ commit }, { $axios }) {
  const ip = await $axios.$get('http://icanhazip.com')
  commit('SET_IP', ip)
}</syntaxhighlight>
==== Store actions ====
<syntaxhighlight lang="javascript">
// In store
{
  actions: {
    async getIP ({ commit }) {
      const ip = await this.$axios.$get('http://icanhazip.com')
      commit('SET_IP', ip)
    }
  }
}</syntaxhighlight>
== 拦截器 ==
{{hc|plugins/axios.js|<syntaxhighlight lang="javascript">
export default function ({ $axios, redirect }) {
  $axios.onRequest(config => {
    console.log('Making request to ' + config.url)
  })
​
  $axios.onError(error => {
    const code = parseInt(error.response && error.response.status)
    if (code === 400) {
      redirect('/400')
    }
  })
}
</syntaxhighlight>}}
== 头部信息 ==
<syntaxhighlight lang="javascript">
// Adds header: `Authorization: 123` to all requests
this.$axios.setHeader('Authorization', '123')
​
// Overrides `Authorization` header with new value
this.$axios.setHeader('Authorization', '456')
​
// Adds header: `Content-Type: application/x-www-form-urlencoded` to only post requests
this.$axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', [
  'post'
])
​
// Removes default Content-Type header from `post` scope
this.$axios.setHeader('Content-Type', false, ['post'])</syntaxhighlight>
== Token ==
<syntaxhighlight lang="javascript">
// Adds header: `Authorization: 123` to all requests
this.$axios.setToken('123')
​
// Overrides `Authorization` header with new value
this.$axios.setToken('456')
​
// Adds header: `Authorization: Bearer 123` to all requests
this.$axios.setToken('123', 'Bearer')
​
// Adds header: `Authorization: Bearer 123` to only post and delete requests
this.$axios.setToken('123', 'Bearer', ['post', 'delete'])
​
// Removes default Authorization header from `common` scope (all requests)
this.$axios.setToken(false)</syntaxhighlight>
== 封装 ==
<blockquote><pre>
<blockquote><pre>
@nuxtjs/axios</pre></blockquote>
@nuxtjs/axios</pre></blockquote>
第32行: 第121行:
const bar= await getBar()</syntaxhighlight>
const bar= await getBar()</syntaxhighlight>


{{leftrightflex|<syntaxhighlight lang="javascript">
{{Double-columns|<syntaxhighlight lang="javascript">
axios.all([
axios.all([
   axios.get('/v2/disease/footer_recommend'),
   axios.get('/v2/disease/footer_recommend'),
第47行: 第136行:
   _self.errorMessage = error
   _self.errorMessage = error
})
})
</syntaxhighlight>|<syntaxhighlight lang="javascript">
</syntaxhighlight>|{{consoleout|<pre>
Promise.all([
Promise.all([
   axios.get('/v2/disease/footer_recommend'),
   axios.get('/v2/disease/footer_recommend'),
第56行: 第145行:
     HospitalRecommendRand: HospitalRecommendRand.data.data
     HospitalRecommendRand: HospitalRecommendRand.data.data
   }
   }
})</syntaxhighlight>}}}
})</pre>}}}}
 


或者自己封装
或者自己封装

2026年11月26日 (四) 05:34的最新版本

引言

复杂数据格式

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

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

使用方式

Component

asyncData

async asyncData({ $axios }) {
  const ip = await $axios.$get('http://icanhazip.com')
  return { ip }
}

methods/created/mounted

methods: {
  async fetchSomething() {
    const ip = await this.$axios.$get('http://icanhazip.com')
    this.ip = ip
  }
}

Store

nuxtServerInit

async nuxtServerInit ({ commit }, { $axios }) {
  const ip = await $axios.$get('http://icanhazip.com')
  commit('SET_IP', ip)
}

Store actions

// In store
{
  actions: {
    async getIP ({ commit }) {
      const ip = await this.$axios.$get('http://icanhazip.com')
      commit('SET_IP', ip)
    }
  }
}

拦截器

plugins/axios.js
export default function ({ $axios, redirect }) {
  $axios.onRequest(config => {
    console.log('Making request to ' + config.url)
  })
​
  $axios.onError(error => {
    const code = parseInt(error.response && error.response.status)
    if (code === 400) {
      redirect('/400')
    }
  })
}

头部信息

// Adds header: `Authorization: 123` to all requests
this.$axios.setHeader('Authorization', '123')
​
// Overrides `Authorization` header with new value
this.$axios.setHeader('Authorization', '456')
​
// Adds header: `Content-Type: application/x-www-form-urlencoded` to only post requests
this.$axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', [
  'post'
])
​
// Removes default Content-Type header from `post` scope
this.$axios.setHeader('Content-Type', false, ['post'])

Token

// Adds header: `Authorization: 123` to all requests
this.$axios.setToken('123')
​
// Overrides `Authorization` header with new value
this.$axios.setToken('456')
​
// Adds header: `Authorization: Bearer 123` to all requests
this.$axios.setToken('123', 'Bearer')
​
// Adds header: `Authorization: Bearer 123` to only post and delete requests
this.$axios.setToken('123', 'Bearer', ['post', 'delete'])
​
// Removes default Authorization header from `common` scope (all requests)
this.$axios.setToken(false)

封装

@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()
axios.all([
  axios.get('/v2/disease/footer_recommend'),
  axios.get('/v2/hospital/recommend/rand')
]).then(axios.spread(function(
  Disease_footer_recommend,
  HospitalRecommendRand
) {
  _self.Disease_footer_recommend = Disease_footer_recommend.data.data
  console.log(HospitalRecommendRand)
  _self.HospitalRecommendRand = HospitalRecommendRand.data.data
})).catch((error) => {
  console.log(error)
  _self.errorMessage = error
})
Promise.all([
  axios.get('/v2/disease/footer_recommend'),
  axios.get('/v2/hospital/recommend/rand')
]).then(([ Disease_footer_recommend, HospitalRecommendRand]) => {
  return {
    Disease_footer_recommend: Disease_footer_recommend.data.data,
    HospitalRecommendRand: HospitalRecommendRand.data.data
  }
})

或者自己封装

// 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);
  }
};