【问题标题】:API requests are undefined when live, but work on localhostAPI 请求在活动时未定义,但在 localhost 上工作
【发布时间】:2021-05-25 09:10:09
【问题描述】:

我在尝试运行的 node.js/express 应用程序时遇到问题。 在本地主机上运行时,我传递给路由的数据被解析,我能够成功使用 req.body.message。但是在我的实时站点上,这只返回未定义。为什么会这样,我该如何解决?

这是我在本地主机和实时服务器上使用的 node.js 应用程序。

const express = require("express");
const cors = require("cors");
const router = express.Router();
const app = express();

router.post("/send", (req, res) => {
  res.send(`message is ${req.body.message}`);
});

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/", router);
const PORT = 3030;

app.listen(PORT, () => console.log("Server on " + PORT));

如果我在本地主机上使用“message”:“hello”进行 POST,我会收到“message is hello”的响应,但在实时服务器上,我会收到“message is undefined”。

任何建议表示赞赏,干杯。

【问题讨论】:

  • 中间件的顺序在express中很重要。在跨域平台上,你需要在中间件配置之后定义你的路由,或者在 router.post 中将所需的中间件作为参数传递。

标签: javascript node.js express cors


【解决方案1】:
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

尝试将所有这些中间件放在“/send”API 端点之前。还要检查控制台错误,这将为您提供有关错误的更多信息。

【讨论】:

  • 重新排列它们并没有改变任何东西,但是谢谢
【解决方案2】:

我解决了。调用实时 api 时,您需要包含一个斜杠。

例如examplewebsite.com/send 不起作用。但是,examplewebsite.com/send/ 会起作用。

我不太了解服务器的工作原理来解释这一点,但它解决了我的问题。我希望其他有此问题的人可以从我的发现中受益。

【讨论】:

    猜你喜欢
    • 2018-10-17
    • 2020-12-20
    • 2021-03-21
    • 2013-10-01
    • 2020-08-23
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多