admin管理员组文章数量:1323342
I have an axios helper file with a baseURL set in my react project. I have been told to remove the hard coded url and use process.env instead, but when I do this the requests no longer work for fetching the data and I get back a 404 GET error in my app.
import axios from "axios";
// axios.defaults.baseURL = ";;
axios.defaults.baseURL = process.env.REACT_APP_BASE_URL;
export default axios;
.env file in the root of my project looks like this - I am thinking maybe it cant find the .env file, I did install the dotenv library.
REACT_APP_BASE_URL=
I get these errors
GET 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
I have an axios helper file with a baseURL set in my react project. I have been told to remove the hard coded url and use process.env instead, but when I do this the requests no longer work for fetching the data and I get back a 404 GET error in my app.
import axios from "axios";
// axios.defaults.baseURL = "https://example-app-name.";
axios.defaults.baseURL = process.env.REACT_APP_BASE_URL;
export default axios;
.env file in the root of my project looks like this - I am thinking maybe it cant find the .env file, I did install the dotenv library.
REACT_APP_BASE_URL=https://example-app-name.
I get these errors
GET https://example-app-name. 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
Share
Improve this question
asked Mar 17, 2021 at 14:29
walker1walker1
3611 gold badge9 silver badges20 bronze badges
2 Answers
Reset to default 2You want to make sure that dotenv
is imported wherever you're using the environment variables. Or if you're using Webpack you can load it in the plugins part of your Webpack config.
const Dotenv = require("dotenv-webpack");
In webpack.config.js
:
module.exports = {
plugins: [
new Dotenv(),
],
}
Here is a link that talks more about environment variable in React.
When you modify a .env
file, you need to restart the React environment.
Stop the React server.
Add the following line to your
.env
file :REACT_APP_BASE_URL="https://example-app-name."
Be sure to import dotenv where you use the REACT_APP_BASE_URL variable:
require('dotenv').config()
npm start
ORyarn start
本文标签: javascriptaxios baseUrl not working in react when using processenvStack Overflow
版权声明:本文标题:javascript - axios baseUrl not working in react when using process.env - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742133122a2422251.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论