【问题标题】:Why is my GET request not working? - CORS + Express + FetchAPI为什么我的 GET 请求不起作用? - CORS + Express + Fetch API
【发布时间】:2021-11-12 05:20:20
【问题描述】:

我正在尝试从我的客户端 vanilla JS 向我的 ExpressJS 服务器运行一个简单的 GET 请求 - 我的客户端在端口 80 上的 nginx 静态服务器上运行,而我的 Express 服务器在端口 3000 上的 nodejs 上运行。

我不断收到 chrome 错误消息:

GET http://localhost:3000/ net::ERR_CONNECTION_REFUSED

客户端 JS:

async function ping() {
    const response = await fetch('http://localhost:3000');
    return response;
}

服务器端 JS:

const express = require('express');
const cors = require('cors');

const app = express();
const port = 3000;

app.use(express.json);
app.use(cors());

app.get('/', (req, res) => {
    res.send('Hello world!');
});

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

如果有人可以帮助我,将不胜感激,在此先感谢您!

【问题讨论】:

  • 欢迎来到 Stackoverflow! app.use(express.json) 应该是app.use(express.json()),但我不知道这是否已经解决了你的问题。
  • 我已经复制了你的代码,在谷歌浏览器上http://localhost:3000我得到了你好世界
  • 连接被拒绝表明 localhost:3000 上实际上没有服务器运行

标签: node.js express fetch-api connection-refused


【解决方案1】:

我已将您的服务器代码复制到 server.js 文件并将 app.use(express.json) 更改为 app.use(express.json()) 或将其完全删除,打开 http://localhost:3000/ 时我得到了

所以你的代码中唯一的问题是我提到的那一行,顺便说一句,当我复制你的确切代码时,我最终超时并且没有连接被拒绝。

【讨论】:

    【解决方案2】:

    我意识到问题是我的网络设置而不是我的代码,抱歉发布了一个无用的问题。

    【讨论】:

    • 如果您在此答案中添加更多细节,您的问题可能不会那么无用。你必须做什么才能让它工作?此处的详细答案可能会对将来遇到类似问题的其他人有所帮助
    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 2017-01-17
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多