如何在Nuxt.js中使用'env'属性获取newapi?

How to use 'env' property in Nuxt.js to get newapi?

我尝试制作新闻网络应用程序以供使用 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 会自动调用它。

此外,要在生产版本中使用环境变量,它们的名称必须是 prefixed with NUXT_ENV_(即 NUXT_ENV_API_KEY)。请注意,这允许您防止密钥被签入源代码(假设您的 .env 文件也不受源代码控制),但是您的 API 密钥仍然可以在 DevTools 的网络选项卡中观察到。