I have a problem while fetching a file from the local npm server. There is a new project that has a simple fetch with the correct location to file. I'm getting a response as App.js:5 GET http://localhost:3000/returnJsonFiles/json_tire.json 404 (Not Found)
Please help me to fix this issue.
App.js
import React, { Component } from 'react';
export default class Main extends Component {
componentDidMount = () => {
fetch(`./returnJsonFiles/json_tire.json`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.json())
}
render() {
return (
<div>
Lorem
</div>
);
}
}
package.json
{
"name": "test",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Below is a Screenshot with code and directory
Screenshot of code package.json directory
CodePudding user response:
From screenshoot of your code, I assume that you are trying to fetch your json_tire.json file which resides in your src/returnJsonFiles folder. As far as I know, our app that is rendered on the client side can only fetch files that reside in the public folder of our react app. Other than that, the files should be imported. And in your case, should be done as follows:
import jsonTire from './returnJsonFiles/json_tire.json';
and if you insist to use fetch approach, put that file into your app's public directory:
app-root
- node-modules
- public
- returnJsonFiles
- json_tire.json // <---- put here
- src