我正在尝试在本地文件中发出请求,但是我不知道何时尝试在计算机上显示错误。是否可以在项目中提取文件?
// Option 1 componentDidMount() { fetch('./movies.json') .then(res => res.json()) .then((data) => { console.log(data) }); } error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json()) // Option 2 componentDidMount() { fetch('./movies.json', { headers : { 'Content-Type': 'application/json', 'Accept': 'application/json' } }) .then( res => res.json()) .then((data) => { console.log(data); }); } error1: GET http://localhost:3000/movies.json 404 (Not Found) at App.js:15 --> fetch('./movies.json', { error2: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json()) // This works componentDidMount() { fetch('https://facebook.github.io/react-native/movies.json') .then( res => res.json() ) .then( (data) => { console.log(data) }) }
您的JSON文件需要由服务器提供服务,因此您需要快速服务器(或任何其他服务器)。在这个例子中,我们使用 express 。
注意: 您也可以下载git repo
App.js文件
import React, { Component } from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: null }; } componentDidMount() { const myHeaders = new Headers({ "Content-Type": "application/json", Accept: "application/json" }); fetch("http://localhost:5000/movie", { headers: myHeaders, }) .then(response => { console.log(response); return response.json(); }) .then(data => { console.log(data); this.setState({ data }); }); } render() { return <div className="App">{JSON.stringify(this.state.data)}</div>; } } export default App;
server.js
var express = require("express"); var data = require('./movie.json'); // your json file path var app = express(); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.get("/movie", function(req, res, next) { res.send(data); }); app.listen(5000, () => console.log('Example app listening on port 5000!'))