无法通过 axios 从本地 json 文件中获取数据 [英] Unable to fetch data from local json file by axios

查看:64
本文介绍了无法通过 axios 从本地 json 文件中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 axios 库从本地 json 文件中获取数据,但是当我发出 get 请求时,它给我错误 404 not found.这是我的文件结构.

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??

推荐答案

如果您使用 create-react-app 命令创建了此文件结构,则必须将您的 json 文件添加到公共文件夹中.然后像波纹管一样改变你的 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);
   })

这篇关于无法通过 axios 从本地 json 文件中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆