Guest User

Untitled

a guest
Apr 24th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. // Option 1
  2. componentDidMount() {
  3. fetch('./movies.json')
  4. .then(res => res.json())
  5. .then((data) => {
  6. console.log(data)
  7. });
  8. }
  9.  
  10. error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json())
  11.  
  12. // Option 2
  13. componentDidMount() {
  14. fetch('./movies.json', {
  15. headers : {
  16. 'Content-Type': 'application/json',
  17. 'Accept': 'application/json'
  18. }
  19. })
  20. .then( res => res.json())
  21. .then((data) => {
  22. console.log(data);
  23. });
  24. }
  25.  
  26. error1: GET http://localhost:3000/movies.json 404 (Not Found) at App.js:15 --> fetch('./movies.json', {
  27. error2: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json())
  28.  
  29.  
  30. // This works
  31. componentDidMount() {
  32. fetch('https://facebook.github.io/react-native/movies.json')
  33. .then( res => res.json() )
  34. .then( (data) => {
  35. console.log(data)
  36. })
  37. }
  38.  
  39. import React, { Component } from 'react';
  40.  
  41. class App extends React.Component {
  42. constructor(props) {
  43. super(props);
  44. this.state = {
  45. data: null
  46. };
  47. }
  48.  
  49. componentDidMount() {
  50. const myHeaders = new Headers({
  51. "Content-Type": "application/json",
  52. Accept: "application/json"
  53. });
  54.  
  55. fetch("http://localhost:5000/movie", {
  56. headers: myHeaders,
  57.  
  58. })
  59. .then(response => {
  60. console.log(response);
  61. return response.json();
  62. })
  63. .then(data => {
  64. console.log(data);
  65. this.setState({ data });
  66. });
  67. }
  68.  
  69. render() {
  70. return <div className="App">{JSON.stringify(this.state.data)}</div>;
  71. }
  72. }
  73.  
  74. export default App;
  75.  
  76. var express = require("express");
  77. var data = require('./movie.json'); // your json file path
  78. var app = express();
  79.  
  80.  
  81. app.use(function(req, res, next) {
  82. res.header("Access-Control-Allow-Origin", "*");
  83. res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  84. next();
  85. });
  86.  
  87. app.get("/movie", function(req, res, next) {
  88. res.send(data);
  89. });
  90.  
  91. app.listen(5000, () => console.log('Example app listening on port 5000!'))
Add Comment
Please, Sign In to add comment