PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 22, 2022

[FIXED] how to solve API key 401 error in env file in React?

 August 22, 2022     api, environment-variables, reactjs     No comments   

Issue

I'm making a website with NewsAPI.

If the API key is placed in the component, it works.

However, if I import it from the .env file, it doesn't work and I get a 401 error.

I rechecked my API key several times.

I added dotenv in my project and I think I did everything but I still got the error.

line 6: console.log() works well. it shows my API key.

Thank you

[App.js]

import axios from "axios";
import React, { useState } from "react";
import dotenv from "dotenv";

dotenv.config();
console.log(process.env.REACT_APP_API_KEY);

function App() {
  const [data, setData] = useState(null);
  const onClick = async () => {
    try {
      const response = await axios
        .get(
          "https://newsapi.org/v2/top-headlines?country=kr&apiKey=process.env.REACT_APP_API_KEY"
        )
        .then((response) => {
          setData(response.data);
        });
    } catch (e) {
      console.log(e);
    }
  };
  return (
    <div>
      <div>
        <button onClick={onClick}>News</button>
      </div>
      {data && (
        <textarea
          rows={7}
          value={JSON.stringify(data, null, 2)}
          readOnly={true}
        />
      )}
    </div>
  );
}

export default App;

Error:

Console

Network


Solution

you should use string interpolation in you url like this: 'https://newsapi.org/v2/top-headlines?country=kr&apiKey=${process.env.REACT_APP_API_KEY}'



Answered By - DimitriWdev
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing