我试图将其添加到
nuxt.config.js中:
asyncData(context) {
return context.$axios
.get('/api/house', {
headers: {
'X-AUTH-TOKEN': '######',
'Content-Type': 'application/json',
},
})
.then((res) => {
return { fetchedData: res.data.page.meta }
})
},
就像我认为每个Axios
axios: {
headers: {
common: {
'X-AUTH-TOKEN': '###################',
'Content-Type': 'application/json',
},
},
},
请求都会有令牌服务器端而不会丢失,但它行不通,但它行不通。因此,我试图设置一个axios Interceptor制作
GET
并将其添加到nuxt.config.js:
:axios.js
myMyAxios.js
:
plugins: [
{ src: '~/plugins/axios.js' },
]
但是,每次我刷新我的nuxt页面时,结果仍然相同,令牌消失了,因为我使用import axios from 'axios'
const AUTH_TOKEN = '#######################'
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/json'
页面不呈现。
如何使用asyncData
设置我的元描述,即使我刷新了浏览器,也可以将令牌添加到每个请求中?
eDit
在这里,我在NUXT页面中对Meta标签的cliend side请求:
asyncData
GET
当然,您可以进行编码<script>
export default {
layout: 'house',
asyncData(context) {
return context.$axios
.get('/api/house', {
headers: {
'X-AUTH-TOKEN': '### TOKEN HARDCODED ###',
'Content-Type': 'application/json',
},
})
.then((res) => {
return { fetchedData: res.data.page.meta }
})
},
data() {
return {
route: 'house',
fetchedData: [],
}
},
head() {
return {
title: this.fetchedData.title,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: this.fetchedData.description },
],
}
},
}
</script>
,但是在这里,我向您展示了如何使用ENV变量。
这是
<template>
<div>
<p>fetched data below</p>
<p>{{ fetchedData }}</p>
</div>
</template>
<script>
export default {
async asyncData({ $axios, $config: { secureToken } }) { // import your env varibles here
const response = await $axios.$get( // $get shortcut, https://axios.nuxtjs.org/usage#-shortcuts
'https://jsonplaceholder.typicode.com/todos/1',
{
headers: {
'X-AUTH-TOKEN': secureToken,
'Content-Type': 'application/json',
},
}
)
return { fetchedData: response }
},
}
</script>
文件的一部分
secureToken
您应该放入
nuxt.config.js
export default {
publicRuntimeConfig: {
secureToken: process.env.SECURE_TOKEN,
},
...
}
当然,这将需要从
.env
(默认行为)中列入黑名单。我为示例目的提出了它,不要公开公开。使用服务器上的ENV变量! :)
在此操作时,您可以研究一些Axios全局配置。让我知道,在继续之前,这是否正常工作。