Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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)
- })
- }
- 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;
- 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!'))
Add Comment
Please, Sign In to add comment