When you need to read a json file in your project, it is easy to get the idea using fetch or axios.
For example, we have data.json.
{
"name": "Hello World",
"age": 18
}
Use fetch to read.
fetch('https://server.com/data.json')
.then((response) => response.json())
.then((json) => console.log(json));
It works when your project is running in web browser environment, but when your project is running in hybrid environment, it is file protocol instead of http protocol. You will get cors error.
You can use script tag to fix this problem.
Change data.json to data.js
window.config = {
"name": "Hello World",
"age": 18
}
Add script tag in your html file template.
<!-- <script src="./data.js"> </script>-->
<script>
document.write('<script src="./data.js?t=' + new Date().getTime() + '"><\/script>')
</script>
Now you can read data from window object in your javascript code.
const data = window.config
console.log(data)
Top comments (1)
Best content thank you for posting. Best software Training institute in chennai for all the software related courses.