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> | |||
2020年7月23日 (四) 12:13的最新版本
引言
npm install @nuxtjs/axios @nuxtjs/proxy --save
nuxt.conf.js
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
axios: {
proxy: true,
prefix: '/api', // url 添加前缀 /api
credentials: true // 示跨域请求凭证
},
proxy: {
'/api': {
target: 'http://192.168.1.10:3000',
changeOrigin: true,
pathRewrite: {
'^/api': '/',
}
}
}
build: {
vendor: ["axios"]
}
axios
封装
import axios from 'axios'
import { userAuth } from "@/utils/auth";
const service = axios.create({
baseURL: 'http://192.168.1.10:3000',
timeout: 30000,
headers: {'Authorization': 'Bearer ' + userAuth.getToken},
})
export default service
plugins/axios.js
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");
}
});
}
在 asyncData 里使用
async asyncData({ $axios }) {
const ip = await $axios.get('http://***.com')
return { ip }
}
在 asyncData 外使用
methods: {
async fetchSomething() {
const ip = await this.$axios.get('http://***.com')
this.ip = ip
}
}
No categories