使用mongoose发送Post Request时,Insomnia中接收到空值,如何修复?

o7jaxewo  于 2023-05-29  发布在  Go
关注(0)|答案(1)|浏览(125)

我正在使用失眠症,我想让它把我在指南针中添加的用户名发送给我,但是当我这样做的时候,它却返回为null。
我一直在绞尽脑汁,但没有成功。

这是我的index.js

import cors from "cors";
import mongoose from "mongoose";
import express from "express";
import bodyParser from "body-parser";
import * as dotenv from 'dotenv'
import morgan from "morgan";
import { fileURLToPath } from "url";
import path from "path"
import { userRouter } from "./controllers/auth.js";

/* CONFIGURATIONS */

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config({ debug: true });

const app = express();

app.use(express.json());
app.use(morgan("common"));
app.use(bodyParser.json({limit:"30mb", extended:true}));
app.use(bodyParser.urlencoded({limit:"30mb", extended:true}));
app.use(cors());

/* ROUTES */

app.use("/auth", userRouter)

 /* MONGOOSE SETUP */

 const PORT = process.env.PORT;
 mongoose.connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
 }).then(() => {
    app.listen(PORT,() => console.log(`Server Started! On Port: ${PORT}`))
}).catch((error) => console.log(`${error} did not connect`))

我的auth.js

import express from "express";
import jwt from "jsonwebtoken"
import UserModel from "../models/user.js"

const router = express.Router();

/* REGISTER USER */

router.post("/register", async(req,res) => {

    const { username, password } = req.body;

    const user = await UserModel.findOne({ username:username });
    res.json(user)
});

export { router as userRouter };

我的模型/架构

import mongoose from "mongoose";

const { Schema } = mongoose;

const UserSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
    }
})

const UserModel = mongoose.model('Users', UserSchema)
export default UserModel

This is the respose in insomniaThis is the info I added in compass
我不知道我的错误是在“export { router as userRouter }”还是“app.use(“/auth”,userRouter)”中

13z8s7eq

13z8s7eq1#

根据您提供的代码,问题可能在于您处理数据库连接和环境变量的方式。
首先,确保正确设置了.env文件,并且正确配置了MONGO_URL变量。确保MongoDB服务器正在运行并可访问。
接下来,确保您已经导入了所需的包,并在index.js文件中正确设置了必要的中间件。下面是代码的更新版本,其中包含了这些更改:

import cors from "cors";
import mongoose from "mongoose";
import express from "express";
import bodyParser from "body-parser";
import dotenv from 'dotenv';
import morgan from "morgan";
import { fileURLToPath } from "url";
import path from "path";
import { userRouter } from "./controllers/auth.js";

dotenv.config({ debug: true });

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();

app.use(express.json());
app.use(morgan("common"));
app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());

app.use("/auth", userRouter);

const PORT = process.env.PORT || 3000;

mongoose
  .connect(process.env.MONGO_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    app.listen(PORT, () => console.log(`Server started! On Port: ${PORT}`));
  })
  .catch((error) => console.log(`${error} did not connect`));

通过运行npm install或yarn install,确保安装了必要的包(dotenv,cors,mongoose,express,body-parser,morgan)。
仔细检查.env文件,确保它包含正确的值,特别是MONGO_URL。
通过这些更改,您的服务器应该能够连接到MongoDB数据库并正确处理请求。

相关问题