【问题标题】:Front End API can't find Back End Endpoint前端 API 找不到后端端点
【发布时间】:2020-08-13 23:11:24
【问题描述】:

我正在尝试将 API 调用链接到我的后端以测试我的服务器是否正在运行。我在前端使用 React,在后端使用带有 express 的 Node.js。

我的后端端点很简单:

app.get('/', (req, res) => {
    console.log('hit')
    const name = req.query.name || 'World';
    res.setHeader('Content-Type', 'application/json');
    res.send({
        greeting: `Hello ${name}!`,
    });
}); 

我在前端提出请求:

  React.useEffect(() => {
    fetch('http://localhost:3001//')
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      })
      .catch(console.log('error'));
  });

我添加了控制台日志以尝试追踪错误。我将“错误”记录到控制台。 此外,我收到控制台错误:

Access to fetch at 'http://localhost:3001/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
manifest.json:1 GET http://localhost:3000/manifest.json 404 (Not Found)
manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.

我之前没见过这个 manifest.json 警告。

【问题讨论】:

标签: javascript node.js reactjs express


【解决方案1】:

我认为这是因为前端的 fetch 调用的是 http://localhost:3000(3000 可能是您前端的端口)。所以你的 fetch 不针对后端。

所以你需要做这样的事情:

fetch('http://localhost:8000') // etc...

8000 更改为您的后端正在侦听的任何端口。

更新

对于第二个问题,就像错误消息说您应该设置 Access-Control-Allow-Origin 标头,以便后端知道允许您的前端向它发出请求。

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

因此,您可以将上述行放在后端的 '/' 路由中,或者您可以创建一些中间件,这样您就不必为每个请求都设置它:No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

【讨论】:

  • 这取得了一些进展。我知道看到控制台日志“命中”,所以我知道我的服务器被命中,但我仍然看到有关 manifest.json 的错误消息。现在有一个新错误(见上文)。
  • 谢谢。我仍然有 manifest.json 的问题,但现在我收到了来自服务器的响应。
【解决方案2】:

两件事。首先,您需要在服务器的响应中添加一个'Access-Control-Allow-Origin' 标头。其次,您缺少manifest.json,因此您必须添加它。 CRA 创建的默认是:

{
  "short_name": "React App",
  "name": "Create React App Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    }
  ],
  "start_url": "./index.html",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}

然后你把它放在你的/public 文件夹中。您还必须将此链接放入您的index.html

<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2018-12-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    相关资源
    最近更新 更多