.env.development

Im Frontend legen wir eine neue Datei .env.development mit folgendem Inhalt an: 

.env.development
				
					# REACT API
NEXT_PUBLIC_BACKEND_URL=http://localhost:8800
NEXT_PUBLIC_API_URL=http://localhost:8800/api
NEXT_PUBLIC_FRONTEND_URL=http://localhost:3300
				
			

axios.js

Die Umgebungsvariablen, die wir in .env.development hinzugefügt haben, werden im folgenden in der axios.js-Datei verwendet, die wir in api/axios.js anlegen:
axios.js
				
					import Axios from "axios";

const axios = Axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_URL,
  headers: {
    "X-Requested-With": "XMLHttpRequest"
  }
});

axios.defaults.withCredentials = true;

export default axios;
				
			

page.js

Vom Frontend aus callen wir jetzt die Route /api/hello-frontend im File app/page.js. Der Code sieht dann so aus:
page.js
				
					"use client";

import axios from "./api/axios";
import { useEffect } from "react";

export default function Home() {
  useEffect(() => {
    axios
      .get(`http://localhost:8800/api/hello-frontend`)
      .then((response) => {
        if (response?.status === 200) {
        }
      })
      .catch((error) => {
        if (error?.response?.status !== 422) throw error;
      });
  });

  return (
    <main>
      <h1>CORS-Error</h1>
      <p>
        This page makes a GET-request to{" "}
        <i>http://localhost:8800/api/hello-frontend</i>.
      </p>
    </main>
  );
}