Fetch local JSON file from public folder ReactJS - javascript

I have a problem since two days; I want read a local JSON from my public folder on my React application created with react-app.
This is my project structure:
public
data
mato.json (my .JSON file)
src
components
App.js
Why I put my file in public folder? If I build my project with file in src folder, my file will be include in the generated main.js by the command yarn build.
I want modify my json file without always rebuild my app.
So I can't use code like:
import Data from './mato.json'
…or:
export default { 'mydata' : 'content of mato.json'}
import data from 'mydata';
I tried to fetch my .json file but "file scheme" isn't friend with fetch() & chrome..
(Chrome error: “index.js:6 Fetch API cannot load file:///D:/projects/data/mato.json. URL scheme "file" is not supported.”)
This is my code for fetch:
fetch(`${process.env.PUBLIC_URL}/data/mato.json`)
.then((r) => r.json())
.then((data) =>{
ReactDOM.render(<App appData={JSON.stringify(data)}/>, document.getElementById('root'));
})
It's only works with Firefox. I also tried mode: 'cors' does not better.
And of course I don't have any server — it's a local project — so if someone knows how I can read my JSON file locally I will much appreciate.

I think your fetch argument is wrong. It should be
fetch('data/mato.json')

You also need to pass in some headers indicating the Content-Type and Accept as application/json to tell your client that you are trying to access and accept some JSON resource from a server.
const getData=()=>{
fetch('data/mato.json'
,{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
)
.then(function(response){
console.log(response)
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
useEffect(()=>{
getData()
},[])

As long as data files are placed in public folder, it should work in Chrome also as in my project.
So, fetch('data/mato.json') is enough for it.

give your JSON file name which is present in the public folder and store the data links
componentDidMount() {
fetch("./url.json")
.then((res) => res.json())
.then((data) => {
this.setState({ links: data });
console.log(this.state);
});
}

why using fetch? I think the speed is slow...
I think this solution would be better...
you can add this line into your index.html:
<script type="text/javascript" src="settings.js"></script>
then in settings.js you can do this:
window.globalTS= {
"site_url": "hi.com",
"home_url": "hello.com"
};
now in your components you can get to variables like this:
console.log(window.globalTS.site_url);
share and comment me your idea, thanks!

Related

Next.js - API call from different page is not loading the data

Hello everyone I am extremely new at the Next.js world.
I am using the getStaticProps() to make an API call and in order to make it little organized, i have created a separate page "git" under "pages" folder and here is my code:
function Git({ stars }) {
return <div>Next stars: {stars}</div>
}
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const json = await res.json()
return { stars: json.stargazers_count }
}
export default Git
And i am trying to load the API data to the index.js file under the "pages" folder.
Inside the index.js file, i am using below to load the API data from the "Git" page
import fetch from "isomorphic-unfetch"
import Git from './Git'
And under the following
render () {
return (
<Git />
On the browser, i am not seeing the API data but i am seeing the HTML from the "Git" page
<div>Next stars: </div>
Is there any way if i can load the API data from different page to the index.js page?
However, if i directly access the page for example: http://0.0.0.0:3000/Git then i get the proper API data.
Issue
The issue is about the API data in the page "Git" is not getting passed to the main page "index.js" is there any way if i can pass the data from the "Git" to the "index.js"
I resolved it by putting the following code in the index.js file
const gitData = await Git.getInitialProps();
And that's where I want to print it out
<Git {...this.props.gitData}/>

How to fetch files from CDN with NuxtJS content module?

I want to fetch files from another server (e.g. a CDN) with the #nuxtjs/content module so that the .md files can be managed independently without Nuxt.js.
My current nuxt.config.js file looks like this:
export default {
...
content: {
dir: 'http://some-cdn.xyz/content/'
},
...
}
Now I want to load the content in the pages/_slug.vue file:
<template>
<div>
<NuxtContent :document="doc" />
</div>
</template>
<script>
export default {
async asyncData({ $content, params }) {
const doc = await $content(params.slug || 'index').fetch();
return { doc };
},
};
</script>
Now when I type in http://localhost:3000/some-page, I should get the corresponding file (some-page.md) from the CDN. Instead, I get this error from Nuxt.js: /some-page not found.
What should I do to get it working and is this even possible with my current setup?
As told here: https://github.com/nuxt/content/issues/237
This is not doable with the content module and is not planned to be done neither. A solution would be to manually fetch the files during the build time or alike.
You can maybe get some inspiration from this comment: https://github.com/nuxt/content/issues/37#issuecomment-664331854 or use another markdown parser.
Since #nuxtjs/content can't fetch files from another server, I used the marked.js library instead.

Using PHP scripts in Vue

I have Vue app that has to use some PHP scripts. If I place them on server everything works fine and I am able to make Axios request like:
this.$http
.post("http://my-domain.com/scripts/news.php", {
action: "getAll"
})
Still, I would like to have those scripts in my local development environment and use them like this:
this.$http
.post("/scripts/news.php", {
action: "getAll"
})
with scripts placed in public/scripts. When tried with PHP dev server or Apache I could only use them when requesting http://localhost/scripts/news.php and proxing PHP server with vue.config.js, but it is not useful since I would need to change that when switching to production.
How to configrue it properly?
try setting up the base url of axios.
import axios from 'axios'
window.axios.defaults.headers.common = {'X-Requested-With': 'XMLHttpRequest'}
window.axios.defaults.baseURL = (process.env.NODE_ENV !== 'production') ? 'http://my-domain.com/' : ''

Where to store API URL in Cypress?

I'm new to Cypress and want to know where's the place I should put all of my external URLs in?
In my website, we have separated URLs for the web, and another one for APIs.
Let's say they're:
App URL: https://app.com
API URL: https://api.myapi.com
I know I can put my app URL in baseUrl in cypress.json, and I've put all my subdirectory e.g. /products /users in the env variables session. Because cy.visit() automatically utilize this baseUrl, it's good for me now.
What I struck now is where to place my API URLs properly. I don't feel like put the fullpath like:
https://api.myapi.com/products
https://api.myapi.com/users
https://api.myapi.com/users/1/edit
is not a good idea, since I repeated the API baseUrl everywhere. And if I split it into apiBaseUrl and the sub part /products, I'm now have to build up the URL myself every time I want to watch it like
cy.route(`${Cypress.env('apiBaseUrl')}${Cypress.env('apiUrl').getProducts}`);
because my apiBaseUrl is not baseUrl. This make it even harder than the above method.
Any suggestion?
I found a quite simple solution. Just simply put your API backend URL right next to the (web frontend) cypress 'baseUrl'. My cypress.json looks like this:
{
"baseUrl": "http://localhost:3001/",
"backendBaseURL": "http://localhost:8080/api/v2",
"env": {
"someDummyEnvironemntVar": "fooBar"
},
"testFiles": "**/*.*",
"watchForFileChanges": true
}
Both can be accessed anywhere in Cypress tests:
Cypress.env('someDummyEnvironemntVar') => "fooBar"
Cypress.config('backendBaseURL') => "http://localhost:8080/api/v2"
We have a separate file called settings.js (cypress/settings.js). Which holds the configuration for the API:
export const apiUri = 'APIURL'
export const apiOauthSecret = 'TOKEN'
To actually use the variable apiUri we import it in the file where we want to use it:
import {apiUri, apiOauthSecret} from '../settings'
Cypress.Commands.add('apiRequest', (endPoint, options) => {
const token = options.token || JSON.parse(window.sessionStorage.getItem('oauth-token') || '{}').accessToken
if (token) {
return cy.request({
failOnStatusCode: false,
...requestOptions({
...options,
token
}),
url: `${apiUri}/${endPoint}`
})
}
return cy
})
This results in being able to use apiUri and baseUrl next to eachother

Using angular 2 http offline when loading JSON in local project folder

I have been trying loading a local json file present in my project folder of Angular 2 using http get method. Look at the following example code snippet:
private _productURL = 'api/products/products.json';
getProducts(): Observable<any> {
return this._http.get(this._productURL).map((response : Response) => <IProduct[]> response.json())
.do(data =>console.log(JSON.stringify(data))).catch(this.handleError);
}
Now when I'm trying to load it with internet connected, it's working. But when I'm turing on the offline checkbox from the browser developer options(https://developers.google.com/web/tools/chrome-devtools/network-performance/reference#offline), the json stops loading again. It starts showing me error in console about No internet connection and doesn't load anything.
Is there any other way to do this? or using http get..how to do it?
You can import a json file if you do as follows:
create a json-typings.d.ts file with:
declare module "*.json" {
const value: any;
export default value;
}
this is a wildcard module definition that allows us to import non javascript files in this case JSON files.
you should now be able to import json files to your project:
import * as products from "./products.json";

Categories