【问题标题】:Express API wont take any requests from POSTMANExpress API 不会接受来自 POSTMAN 的任何请求
【发布时间】:2021-04-08 23:56:41
【问题描述】:

我一直在尝试开发用于 MEAN 堆栈应用程序的 API。 API 处理用户注册和身份验证。 真正有趣的是它没有接受 Postman 的任何请求。即使是带有响应的简单“/”获取请求也不起作用。我在邮递员上遇到的错误如下

我的 index.js 如下:

const exp = require('express');
const bp = require('body-parser');
const { success, error } = require('consola')
const { connect } = require('mongoose');

// Bring in the app constants
const { DB, PORT } = require("./config");

// Initialize the application
const app = exp();

// Call the middleware
app.use(cors());
app.use(bp.json);

// User Router Middleware
app.use("/api/users", require("./routes/users"));
app.use("/basic", require("./routes/basic"));

// Connect to the database

const startApp = async () => {
    try {
      // Connection With DB
      await connect(DB, {
        useFindAndModify: true,
        useUnifiedTopology: true,
        useNewUrlParser: true
      });
  
      success({
        message: `Successfully connected with the Database \n${DB}`,
        badge: true
      });
  
      // Start Listenting for the server on PORT
      app.listen(PORT, () =>
        success({ message: `Server started on PORT ${PORT}`, badge: true })
      );
    } catch (err) {
      error({
        message: `Unable to connect with Database \n${err}`,
        badge: true
      });
      startApp();
    }
  };



startApp();

我的基本路由如下,它本身甚至不适合我:


router.get('/', function (req, res) {
    res.send('Hello World!' + req.body)
  })

module.exports = router;

邮递员回复如下截图:

服务器似乎正在运行,但似乎只是拒绝所有请求。

mongodb://localhost:27017/node-auth


 SUCCESS  Server started on PORT 3000                                                 16:26:36  

【问题讨论】:

  • 错误状态码是什么?请提供带有错误详细信息的图片
  • 你在localhost:3000/ 上得到了什么?
  • 你正在调用 app.use(cors());但不导入 cors 函数。 docs
  • 你的路由器是在哪里定义的?路由器内部的/ 并不意味着邮递员上的http://localhost:3000/
  • 路由器定义在文件开头,如“const router = require('express').Router();”

标签: javascript express postman middleware


【解决方案1】:

您在基本路由器中导入 express 吗?
它应该看起来像这样:

 const express = require("express");
 const router = express.Router();
  
 router.get("/", (req, res) => {
   res.send(`Hello World! ${req.body}`);
 });
          
 module.exports = router;

【讨论】:

  • 你好,是进口的,是的。 const router = require('express').Router();但还是不行
【解决方案2】:

我很抱歉。

我缺少一个 () 大括号,它允许应用程序运行但不正确。有时只需要另一只眼睛。

之前: app.use(bp.json); 之后:app.use(bp.json());

现在完美运行。

【讨论】:

  • 请不要发布错字答案;如果可能,只需删除问题。
【解决方案3】:

您没有使用 index.js 中同一个 express 实例中的 router

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 2018-09-25
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 2015-04-02
    相关资源
    最近更新 更多