【问题标题】:How to use 'env' property in Nuxt.js to get newapi?如何在 Nuxt.js 中使用“env”属性来获取 newapi?
【发布时间】:2021-04-04 14:06:04
【问题描述】:

我尝试让新闻网络应用程序使用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>

【问题讨论】:

    标签: javascript typescript vue.js nuxt.js middleware


    【解决方案1】:

    您无需调用require('dotenv').config(),因为 Nuxt 会自动调用它。

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

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 2023-03-03
      • 1970-01-01
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 2022-08-20
      相关资源
      最近更新 更多