I have been working on creating news web apps that utilize newsapi.org. To protect my API key, I decided to use the env property in Nuxt.Js. However, I am now encountering a 401 status code from the server.
Firstly, I created the .env file in my project directory and added my API_KEY. Then, I installed 'dotenv' using the 'yarn add dotenv' command in VSCode terminal.
In addition, I updated the nuxt.config.ts file. Since I am using TypeScript in my project, all files are dependent on TypeScript.
require('dotenv').config()
const { API_KEY } = process.env
export default {
~~~~~~~~~~
env: {
API_KEY,
},
}
I used Vuex to fetch news information, here is the code snippet.
~/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 }
Lastly, I created a vue file to display the news information.
<template>
<div>
<p>This is NewsApi test page!!</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>
Upon running my app, I encountered a 401 status code and checked the console error message.
{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"
I am unsure why this error has occurred even though I confirmed the proper setting of the API key through console.log.
In index.vue
<script lang='ts'>
~~~~
export default class extend Vue{
mounted(){
console.log(process.env.API_KEY)
}
}
</script>