Node.js/nuxt/跨域:修订间差异
来自康健生活
创建页面,内容为“== 引言 == <blockquote> <syntaxhighlight lang="bash"> npm install @nuxtjs/axios @nuxtjs/proxy --save </syntaxhighlight></blockquote> {{hc|nuxt.conf.js|<syntaxhighl…” |
|||
| 第39行: | 第39行: | ||
}) | }) | ||
export default service</syntaxhighlight> | export default service</syntaxhighlight> | ||
{{hc|plugins/axios.js|<syntaxhighlight lang="javascript"> | |||
export default function({ $axios, redirect }) { | |||
$axios.onResponse(res => { | |||
return res.data | |||
}) | |||
$axios.onError(error => { | |||
const code = parseInt(error.response && error.response.status); | |||
if (code === 400) { | |||
redirect("/400"); | |||
} | |||
}); | |||
}</syntaxhighlight>}} | |||
在 asyncData 里使用 | |||
<syntaxhighlight lang="javascript"> | |||
async asyncData({ $axios }) { | |||
const ip = await $axios.get('http://***.com') | |||
return { ip } | |||
} | |||
</syntaxhighlight> | |||
在 asyncData 外使用 | |||
<syntaxhighlight lang="javascript"> | |||
methods: { | |||
async fetchSomething() { | |||
const ip = await this.$axios.get('http://***.com') | |||
this.ip = ip | |||
} | |||
}</syntaxhighlight> | |||