繁体   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