簡體   English   中英

Fetch 調用返回 react index.html 和 chrome 給出錯誤 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

[英]Fetch call returns react index.html and chrome gives error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

我正在嘗試從我的本地快遞服務器獲取數據,並用反應顯示它,但似乎正在返回反應應用程序的 index.html。 如果我檢查控制台中的網絡選項卡,它顯示有一個名為“projects/”的獲取請求,當我通過 hover 時它顯示“http://localhost:3000/api/projects”。 控制台表明問題出在 react 文件的第 13 行,即“fetch('/api/projects/')”。 我一直在嘗試解決此問題,但似乎無法正確解決。 下面的代碼

表達:

const express = require("express");
const app = express();

app.use(express.json());

let projects = [
  {
    id: 1,
    title: "project1",
    description: "One - description",
    url: "www.One.com"
  },
  {
    id: 2,
    title: "project2",
    description: "Two - description",
    url: "www.Two.com"
  },
  {
    id: 3,
    title: "project3",
    description: "Three - description",
    url: "www.Three.com"
  }
];

app.get("/api/projects", (req, res) => {
  res.json(projects);
});

const PORT = 5000;
app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

反應:

import React from "react";
import "./App.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      projects: []
    };
  }

  componentDidMount() {
    fetch("/api/projects/")
      .then(res => res.json())
      .then(projects =>
        this.setState({ projects }, () =>
          console.log("Projects fetched...", projects)
        )
      );
  }

  render() {
    return (
      <div className="App">
        <h1>Projects</h1>
      </div>
    );
  }
}

export default App;

反應 package.json:

{
  "name": "my-full-stack-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:5000",
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [">0.2%", "not dead", "not op_mini all"],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

您的服務器在端口 5000 上運行,客戶端在端口 3000 上運行。因此,您必須將 api 請求稱為fetch('http://localhost:5000/api/projects/')

如果不指定完整的 URL,請求將被發送到http://localhost:3000/api/projects

您還可以將基礎 URL 存儲在常量中。

import React from 'react';
import './App.css';

const baseUrl = 'http://localhost:5000';

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      projects: []
    }
  }

  componentDidMount() {
    fetch(`${baseUrl}/api/projects/`)
      .then(res => res.json())
      .then(projects => this.setState({ projects }, () => console.log('Projects fetched...', projects)));
  }

  render() {
    return (
      <div className="App">
        <h1>Projects</h1>
      </div>
    );
  }
}

export default App;

似乎這是一個跨域請求。 我按照 expressjs 文檔中的步驟安裝了 cors 中間件,並將其添加到我的 express 文件中並使用了 app.use(cors())。 現在一切正常!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM