[英]How to get Nuxt.js environment variables defined in `env` object?
[英]How to use 'env' property in Nuxt.js to get newapi?
我嘗試制作新聞 web 應用程序以使用newsapi.org。 我想隱藏我的 api_key,所以我決定在 Nuxt.Js 中使用 env 屬性。 但現在我從服務器獲得了 401 狀態碼。
首先,我在項目文件中創建了 .env 文件,並放入了我的 API_KEY。 然后我在 VSCode 終端中安裝了 'dotenv' 使用 'yarn add dotenv' 命令。
我添加了 nuxt.config.ts 文件。 我在我的項目中使用了 TypeScript,所以所有文件都依賴於 TypeScript。
require('dotenv').config()
const { API_KEY } = process.env
export default {
~~~~~~~~~~
env: {
API_KEY,
},
}
我使用 Vuex 來獲取新聞信息。 所以我做了如下代碼。
~/store/getNews.ts
import { MutationTree, ActionTree, GetterTree } from "vuex";
import axios from "axios";
const url = 'http://newsapi.org/v2/top-headlines';
interface RootState { }
export interface NewsArticles {
source?: {}
author?: string
title?: string
description?: string
url?: any
urlToImage?: any
publishedAt?: string
content?: string
}
interface State {
newArticle: NewsArticles
}
export const state = () => ({
newsArticle: []
})
export const getters: GetterTree<State, RootState> = {
newsArticle: (state: State) => state.newArticle
}
export const mutations: MutationTree<State> = {
setNewsArticle: (state: State, newsArticle: NewsArticles) => {
state.newArticle = newsArticle
}
}
export const actions: ActionTree<State, RootState> = {
getNewsArticle: async ({ commit },{params}) => {
try{
const data = await axios.get(url,{params})
commit('setNewsArticle', data.data.articles)
}catch(error){
commit('setNewsArticle',[])
}
}
}
export default { state, getters, mutations, actions }
最后,我制作了 vue 文件來顯示新聞信息,如下所示。
<template>
<div>
<p>this is NewsApi test pages!!</p>
<ul v-for="(item, index) in items" :key="index">
<li>{{ item.title }}</li>
</ul>
</div>
</template>
<script lang="ts">
import { Component, namespace, Vue } from 'nuxt-property-decorator'
import { NewsArticles } from '~/store/getNews'
const getNews = namespace('getNews')
@Component({})
export default class extends Vue {
@getNews.Action getNewsArticle!: Function
@getNews.Getter newsArticle!: NewsArticles
items: any = []
async mounted() {
await this.getNewsArticle({
params: { country: 'jp', category: 'business', apiKey: process.env.API_KEY },
})
this.items = this.newsArticle
}
}
</script>
我運行了我的應用程序,但我得到了 401 狀態代碼,我檢查了控制台錯誤,如下所示。
{status: "error", code: "apiKeyInvalid",…}
code: "apiKeyInvalid"
message: "Your API key is invalid or incorrect. Check your key, or go to https://newsapi.org to create a free API key."
status: "error"
我不知道為什么會發生這個錯誤。 我檢查了 apikey 正確設置以確認 consle.log。
在 index.vue 中
<script lang='ts'>
~~~~
export default class extend Vue{
mounted(){
console.log(process.env.API_KEY)
}
}
</script>
你不需要調用require('dotenv').config()
,因為 Nuxt 會自動調用它。
此外,對於在生產構建中可用的環境變量,它們的名稱必須以NUXT_ENV_
為前綴(即NUXT_ENV_API_KEY
)。 請注意,這允許您防止將密鑰簽入源代碼(假設您的.env
文件也不受源代碼控制),但您的 API 密鑰仍然可以在 DevTools 的“網絡”選項卡中觀察到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.