I’m using React with Typescript and Webpack 5, served with webpack-dev-server. My project structure is as follows:
Project
|-src
| |-(All my code)
|-app.config.json
I keep my backend URLs in a “app.config” file that’s located in the root directory and I need to read it somehow. Since it’s possible that it will change in runtime as I debug different servers, I’d like it to be loaded dynamically and I tried doing so via axios as axios.get('/app.config.json')
However, this results in a 404 Not Found error. Moreover, if I go directly by the address localhost:8080/app.config.json
it will not be there either, as if not included at all when serving. Do I need to somehow include this file in webpack config?
I’d like to add that I would greatly prefer to keep the method of loading this file as axios from the root directory (not in /public, etc.) unless there’s absolutely no fix as other projects in my org follow this pattern and this particular one just doesn’t work after updating to wp5 for some reason.
3
So you wouldn’t typically use axios for something like this. It sounds like you want to read the app.config.json
file’s contents, find the backend URLs, and then for those URLs make various HTTP requests using axios (what it’s more commonly used for).
In JavaScript, you can use node to read a file. See below.
// filereader.js
const fs = require('fs');
fs.readFile('/app.config.json', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
// use results in data to find the URLs and make subsequent HTTP requests via axios
});