.env
REACT_APP_MAPBOX_ACCESS_TOKEN=mytoken
API_URL=http://localhost:1377
.js
// const API_URL = "http://localhost:1337";
export async function listLogEntries() {
const response = await fetch(`${process.env.API_URL}/api/routes`);
return response.json();
}
export async function createLogEntry(entry) {
const response = await fetch(`${process.env.API_URL}/api/routes`, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(entry),
});
return response.json();
}
When I fetch API_URL from.env file I get an error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
But If I use API_URL right away from.js file
const API_URL = "http://localhost:1337";
export async function listLogEntries() {
const response = await fetch(`${API_URL}/api/routes`);
return response.json();
}
export async function createLogEntry(entry) {
const response = await fetch(`${API_URL}/api/routes`, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(entry),
});
return response.json();
}
I don't get that error and my app work as well
You might not implementing dotenv correctly. I implment it this way: Making the topmost import in the server.js file of my node project with the path to the env file. Check it below:-
require('dotenv').config({path: './.env'});
The env file looks like:-
And i am able to use the.env file correctly within the project.
You can check the complete blog out here .
The env module i used is this .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.