【问题标题】:React API communication refuse on cloud IDE (MERN Stack)云IDE(MERN Stack)上的React API通信拒绝
【发布时间】:2021-06-07 05:49:14
【问题描述】:

我正在按照以下教程学习 MERN 堆栈。 https://medium.com/@beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1

我决定使用一个名为 goorm IDE (https://ide.goorm.io) 的云平台 IDE,它类似于 cloud 9 IDE,并且在我按照教程进行操作时,我意识到一个简单的问题,即测试环境略有不同,因为我无法访问我机器上的本地主机(或者至少我不知道如何访问。)

在后端工作并没有太大问题,因为这个 IDE 提供了一个我可以访问的域,我可以只运行 server.js(而不是整个 react 应用程序)并轻松测试 API 端点。 但是现在我在学习前端时运行了整个反应应用程序,我发现当我只运行服务器时,我的 server.js 无法访问,并且我会被拒绝连接,如下所示。

以下代码是我从前端使用的实际代码,以便对服务器进行 API 调用。

axios.post('http://localhost:5000/users/add', user).then(res => console.log(res.data));
// I tried changing the url to external domain.. changing the directory.. with no luck..

下面是 server.js 文件的代码。

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

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

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

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);

const connection = mongoose.connection;
connection.once('open', () => {
    console.log("Mongo DB database connection established successfully");
});

const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);

app.listen(port, process.env.IP, () => {
    console.log(`Server is running on port: ${port}`);
});

下面是我实际尝试进行 API 调用的页面的 url。 https://zimen.run.goorm.io/user

其他环境信息

  • 从 IDE 运行 URL 和端口设置:https://zimen.run.goorm.io:3000
  • React 应用程序目录:root/mern-exercise-tracker/
  • 依赖项:express、create-react-app、mongoose、cors

我想知道在干净的本地环境中重新启动整个项目是否会更好.. 如果有人可以帮忙,将不胜感激。

如果需要任何其他信息,请告诉我,或者您可以在线加入 IDE,因为这是一个云 IDE。

提前谢谢你。

== 更新 ==

抱歉,我忘记附上错误日志了。

xhr.js:178 POST https://localhost:3000/users/add net::ERR_CONNECTION_REFUSED
Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)

【问题讨论】:

  • 尝试调用 api 时遇到什么错误
  • 嗨,Shubham,感谢您的评论。我已经用错误日志更新了问题。

标签: javascript node.js reactjs express


【解决方案1】:

看来你有CORS 错误,我通过在Goolge Chrome 上安装CORS 扩展解决了这个问题

【讨论】:

    【解决方案2】:

    在 Nodejs 服务端设置 PORT=5000,并将 React 前端的默认端口设置为 PORT=3000

    为 Nodejs 和 React 设置您自己的单独自定义“运行 URL 和端口”。

    例子:

    https://[custom-client-side-name].goorm.io

    PORT=3000 的 React 和

    https://[custom-server-side-name].goorm.io

    对于 Nodejs,PORT=5000

    对于 React 端的 Axios 命令,使用:

    axios.post('https://my-server-side.goorm.io/users/add', user).then(res => console.log(res.data));
    

    同样,可以在您设置的自定义网站上找到 React 前端:https://my-client-side.goorm.io/[custom-routes]

    【讨论】:

      猜你喜欢
      • 2020-10-03
      • 2022-06-29
      • 2018-11-08
      • 2018-07-07
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 2021-03-30
      • 2020-05-27
      相关资源
      最近更新 更多