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
Add a ment  | 

2 Answers 2

Reset to default 2

You 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.

  1. Stop the React server.

  2. Add the following line to your .env file :

    REACT_APP_BASE_URL="https://example-app-name."

  3. Be sure to import dotenv where you use the REACT_APP_BASE_URL variable: require('dotenv').config()

  4. npm start OR yarn start

本文标签: javascriptaxios baseUrl not working in react when using processenvStack Overflow