【问题标题】:How to get data from node?如何从节点获取数据?
【发布时间】:2019-10-26 05:19:03
【问题描述】:

问题:我正在使用 fetch API 向节点发送 get 请求,但出现以下错误

阅读代码中的注释

server.js

const express = require('express');

const app = express();
const bodyParser = require('body-parser');

const notes = [
    {id: 0, title: "Dinner", body: "- Chicken - Rice - Potatos"},
    {id: 1, title: "Dinner", body: "- Chicken - Rice - Potatos"}
];

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res, next)=>{
    // Sending data!
    res.json(notes);
})

const port = 3001;

app.listen(port, ()=> console.log(`Server started on port ${port}`));

app.js

class App extends Component{
  state = {
    notes: []
  }

  componentDidMount(){
    // Line where I get the error
    fetch('/')
      .then(resp => resp.json())
      .then(data => this.setState({notes: data}))
  };

【问题讨论】:

  • fetch() 承诺链的末尾放置一个 .catch() 处理程序并记录它报告的确切错误。无论如何,您应该始终有一个 .catch() 处理程序。

标签: javascript reactjs express fetch


【解决方案1】:

错误提示解析的字符串不是 JSON。由于我们没有看到客户端的完整设置,我的猜测是您没有请求开发服务器,这就是您收到错误的原因。

要检查这个尝试:

fetch('/').then(res => res.text()).then(text => console.log(text))

这会将响应输出为纯文本,您将看到您是否请求正确的 URL 并获得您期望的 JSON。如果不这样做,只需将绝对 URL(localhost 或 127.0.0.1 或您为服务器配置的任何内容)与 3001 端口一起使用。

【讨论】:

    【解决方案2】:

    server.js 表明它只有一个端点:/

    这意味着您的 React 应用程序必须由不同的 HTTP 服务器提供服务。

    您说fetch('/'),这是一个相对 URL,所以您从托管 React 应用程序的服务器而不是由 server.js

    创建的服务器请求 /

    这意味着您可能正在获取引导 React 应用程序的 HTML 文档。这跟踪错误消息,指出/ 的文件以< 开头。

    您需要从实际托管它的服务器请求数据:

    `fetch('http://localhost:3001/')`
    

    但是,这将是一个跨域请求,因此您还需要 have server.js give permission to the browser 将 JS 从 React 应用程序公开给 JavaScript。由于您使用的是 Express,因此您可以使用 cors module 执行此操作。

    【讨论】:

    • 这不是问题所在,在我的 package.json 文件中我设置了代理 "proxy": "http://localhost:3001",它将这个 fetch('/') 读取为 fetch('localhost:3001/')。这意味着输入更少
    • @MMasood — 这就是问题所在。 proxy 只会代理 unknown URL。 / 不是未知数。它是引导 React 应用程序的 HTML 文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多