简体   繁体   中英

Read a JSON file in react.js

I have to read JSON file using React.js which is stored in local drive in Mac. I tried using fetch() api but I get data undefined. Heres my code.

fetch('http://localhost:300/107k.json')
    .then(req => console.log(req))
    .then(data => console.log(data))

I am getting data as undefined. How will I be able to read JSON file in react.js?

Just use import instead

import react from 'react'

//... rest of imports

import MyJson from '../path/to/json/107k.json';

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

fetch('http://localhost:300/107k.json')
  .then(res => res.json())
  .then(data => console.log(data))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM