Javascript 如何使用';环境';属性以获取新API?

Javascript 如何使用';环境';属性以获取新API?,javascript,typescript,vue.js,nuxt.js,middleware,Javascript,Typescript,Vue.js,Nuxt.js,Middleware,我尝试制作新闻网络应用程序以供使用 我想隐藏我的api_密钥,所以我决定在Nuxt.Js中使用env属性。 但现在我从服务器上得到了401状态码 首先,我在项目文件中创建了.env文件,并放置了API_密钥。 然后我在VSCode终端中安装了'dotenv'使用'warn add dotenv'命令 我添加了nuxt.config.ts文件。我在我的项目中使用了TypeScript,所以所有文件都依赖于TypeScript require('dotenv').config() const { A

我尝试制作新闻网络应用程序以供使用 我想隐藏我的api_密钥,所以我决定在Nuxt.Js中使用env属性。 但现在我从服务器上得到了401状态码

首先,我在项目文件中创建了.env文件,并放置了API_密钥。 然后我在VSCode终端中安装了'dotenv'使用'warn add dotenv'命令

我添加了nuxt.config.ts文件。我在我的项目中使用了TypeScript,所以所有文件都依赖于TypeScript

require('dotenv').config()
const { API_KEY } = process.env
export default {
 ~~~~~~~~~~
 env: {
    API_KEY,
  },
}
我用Vuex获取新闻信息。 所以我编写了如下代码

{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"
~/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 }
我不知道为什么会发生那个错误。 我检查了apikey的正确设置以确认consle.log

在index.vue中


~~~~
导出默认类扩展Vue{
安装的(){
console.log(process.env.API_KEY)
}
}

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

此外,对于要在生产构建中可用的环境变量,它们的名称必须是(即,
numxt\u env\u API\u KEY
)。注意:这允许您避免将密钥签入源代码(假设您的
.env
文件也不受源代码控制),但您的API密钥仍然可以在DevTools的“网络”选项卡中看到