I am using axios library for fetching data from the local json file but when i make get request it gives me error 404 not found. Here is my file structure.
and i am using this code for fetching the data.
import React from 'react';
import axios from 'axios';
class Login extends React.Component{
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.state = { username: null, password: null };
}
handleSubmit = (e)=>{
e.preventDefault();
var username=e.target.username.value;
var password=e.target.password.value;
axios.get('../data.json')
.then((res)=>{
console.log(res.data);
}).catch((err)=>{
console.log(err);
})
}
render(){
return(
<form onSubmit={this.handleSubmit}>
<input id="username" name="username" type="text" />
<input id="password" name="password" type="text" />
<button>Login!</button>
</form>
);
}
}
export default Login;
How do i solve this issue??
How to Send POST JSON Requests Using Axios. The POST request is used to send data to an endpoint. For example, if we have a registration page where users submit their information, this information can be sent as JSON to the endpoint we specify using a POST JSON request.
Axios cannot read from the file system. It can only make HTTP calls. If you are running in a node environment, look into the fs package, this will let you read from the local file system. Otherwise you will need to expose the json file via a webserver to make it accessible to Axios.
If you created this file structure using create-react-app command you have to add your json files into public folder. then change your axios path like bellow
handleSubmit = (e)=>{
e.preventDefault();
var username=e.target.username.value;
var password=e.target.password.value;
axios.get('./data.json')
.then((res)=>{
console.log(res.data);
}).catch((err)=>{
console.log(err);
})
Are you running the JSON file on the server. Try this command.
json-server -w -p 3001 data.json - runs on port 3001
import React from 'react';
import axios from 'axios';
class Login extends React.Component{
constructor(){
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {username: null, password: null };
}
handleSubmit = (e)=>{
e.preventDefault();
var username=this.refs.username.value;
var password=this.refs.password.value;
axios.get('../data.json')
.then((res)=>{
console.log(cb(res.data));//included the call back method
}
).catch((err)=>{
console.log(err);
}
)
}
render(){
return(
<form>
<input ref="username" type="text" />
<input ref="password" type="text" />
<input type="submit" value="Login" onClick={this.handleSubmit} />
</form>
);
}
}
export default Login;
Hope this works, tried and tested
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With