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:
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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.