Javascript: JSON file reading
Javascript: JSON file reading
Assume the targetJsonFileUrl is declared for the options below:
const targetJsonFileUrl = 'http://myServer.com/data.json';
Options:
1) Fetch command * preferred *
fetch(proxyUrl + targetJsonFileUrl)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
2) Stringify and Parse statement
var object = JSON.stringify(document.activeElement.textContent.replaceAll('\n',''));
var json = JSON.parse(JSON.parse(object));
then access data that is in the json object:
json.items[0].contactInfo.firstName
3) Import statement
import data from
targetJsonFileUrlassert { type: 'json' };
The challenge is CORS errors (Cross Origin Request). CORS errors are usually not a problem when we are fetching data from a server. The best ways to deal with CORS errors are:
1) Have a server side RESTful API written in other server language that has the JSON file that it reads and it gives to your program.Then just call the API for your data.
2) Use a CORS proxy (a.k.a. reverse proxy) server that is in your domain that you call. The proxy server is usually setup with:
npm install http-proxy-middleware
then:
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/api', createProxyMiddleware({ target: 'http://myServer.com.com', changeOrigin: true }));
app.listen(3001, () => {
console.log('Proxy server running on port 3001');
});
This proxy server now listens on port 3001 and forwards requests to http://myServer.com. Your front end application can now make requests to http://localhost:3001/api, and the proxy server will forward the requests to http://myServer.com.
Comments
Post a Comment