Reputation: 135
Hi I am new in react application. I want to set Public_URL in .env file .
.env file (I set my url link)
PUBLIC_URL="http://localhost:8000/api";
Login.tsx file
const response = await fetch("/login", {
method: 'POST',
headers: {'Content-Type': 'application/json'},
credentials: 'include',
body: JSON.stringify({
userName,
password
})
});
When i start the application, My application should be work fine. But In my Login page I submit the Login button My Url call to http://localhost:3000/login. But I need to set http://localhost:8000/api . I don't know how to set it. Please send the correct example.
Package.json
"scripts": {
"start": "env-cmd -f .env react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
Upvotes: 5
Views: 16725
Reputation: 1
**.env File**
REACT_APP_populationInYears_API_URL = 'https://datausa.io/api/data?drilldowns=Nation&measures=Population'
**populationInYears.js File**
import React, { useState } from 'react'
const PopulationInYears = () => {
const apiUrl = process.env.REACT_APP_populationInYears_API_URL;
async function fetchApiData() {
const apiData = await fetch(apiUrl)
console.log(apiData);
const data = await apiData.json();
console.log(data);
}
useState(() => {
fetchApiData();
}, []);
return (`enter code here
<div>PopulationInYears</div>
);
};
export default PopulationInYears;
restart your build after writing the code
Upvotes: 0
Reputation: 1142
You can use custom environment variables for that purpose. Also, notice that your custom environment variables should start REACT_APP_ prefix. This is required to access variables in the application.
Upvotes: 1
Reputation: 109
PUBLIC_URL Reference Documentation
https://create-react-app.dev/docs/using-the-public-folder/
It must be used for external web resource like Icon, Image, CSS. It is meant for internal reference to current web page link.
Upvotes: 1
Reputation: 1634
You can set in .env file another variable for your endpoint, for example:
REACT_APP_API_ENDPOINT=http://localhost:8000/api
PUBLIC_URL
is already used as base url to React get the dependencies of your application.
In your component you can get the environment variable this way:
const { REACT_APP_API_ENDPOINT } = process.env;
const response = await fetch(`${REACT_APP_API_ENDPOINT}/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
userName,
password,
}),
});
Upvotes: 6