0

I'm trying to fetch data from Strapi using Axios for my Vite website, but I get an Error 404 message.

So far I figured out that my REACT_APP_API_URL is giving me undefined when I add "/server" at the end of the localhost address.

What could be the problem?

This is the error I'm getting from Axios:

code
: 
"ERR_BAD_REQUEST"
config
: 
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
: 
"Request failed with status code 404"

This is what I get on the browser when I click the link in the .env file:

{"data":null,"error":{"status":404,"name":"NotFoundError","message":"Not Found","details":{}}}

In my .env file I have:

REACT_APP_API_URL = http://localhost:1337/server

This is the code I'm running:

import React, { useEffect, useState } from "react";
import "./Featured.scss";
import Card from "../Card/Card";
import axios from "axios";

useEffect(() => {
    const fetchData = async () => {
      try {
        const data = await axios.get(process.env.REACT_APP_API_URL + "/products", {
          headers: {
            Authorization: "bearer " + process.env.REACT_APP_API_TOKEN,
          },
        });
        console.log(data)
      } catch (err) {
        console.log(err);
      }
    };
    fetchData();
  }, [])
Sibusiso
  • 19
  • 6

1 Answers1

0

I figured it out. Vite does not use process.env, instead it uses import.meta.env and

The .env variables are written this way:

Instead of this

REACT_APP_ API_KEY = 1234567890..

Use this

VITE_API_KEY = 1234567890..

I also learned that you don't need to change your variables in .env if you use the (https://www.npmjs.com/package/vite-plugin-env-compatible) plugin.

Here's how it works: First, install the vite-plugin-env-compatible package:

npm i vite-plugin-env-compatible

Next, go to the vite.config.js file in the root folder of the project and add the following code:

import envCompatible from 'vite-plugin-env-compatible';

export default defineConfig({
    ...
  envPrefix: 'REACT_APP_',

  plugins: [
    react(),
    envCompatible
  ],
});

The envPrefix property will tell Vite to use variables with a REACT_APP_ prefix. Now, you can use environment variables in your project without changing names. However, you’ll still have to replace process.env with import.meta.env in your code.

Sibusiso
  • 19
  • 6