Mongo db 查询(快速服务器)通过浏览器请求失败,但正在处理邮递员(不是 CORS 错误)

发布时间:2021-03-07 23:51

我在 Ubuntu 20.04 上运行的 express 应用程序遇到以下问题。

我有一个用 node.js 和 typescript 设置的 express.js 服务器。我正在使用 mongo db 和 mongoose。

问题

<块引用>

当我通过浏览器向我的服务器应用程序发送请求时 登录(例如),猫鼬函数 findOne 失败并返回 检索到的文档始终为 null。

这不是通过邮递员发生的!!

此代码也在我的其他 WINDOWS 机器上正确运行!

机器设置

<块引用>

操作系统:Ubuntu 20.04

节点:15.11.0

MongoDB 外壳:4.4.4

猫鼬:5.11.19

代码

export const login = async (
    request: Request,
    response: Response,
    next: NextFunction
) => {
    const { error, value } = UserLoginValidation.validate(request.body);

    if (error) {
        const commonError: ICommonError = {
            statusCode: 400,
            message: error.details[0].message
        };
        return response.status(400).json(commonError);
    }

    const user = await UserModel.findOne({ email: value.email })
    console.log(user);

    //HERE IS THE PROBLEM!!! USER IS ALWAYS NULL!!!

    if (!user) {
        const commonError: ICommonError = {
            statusCode: 401,
            message: "Email and password, does not match."
        };
        return response.status(401).json(commonError);
    }

    const match = await compare(value.password, user.password);

    if (!match) {
        const commonError: ICommonError = {
            statusCode: 401,
            message: "Email and password, does not match."
        };
        return response.status(401).json(commonError);
    }

    try {
        const token = jwt.sign({ userId: user.id }, <string>process.env.JWT_SECRET, { expiresIn: "1d" });

        response.setHeader("X-Access-Token", `Bearer ${token}`);

        return response.status(200).send({
            message: 'Login Successful!', user: {
                _id: user._id,
                firstName: user.firstName,
                lastName: user.lastName,
                email: user.email
            }
        })
    } catch (e) {
        const commonError: ICommonError = {
            statusCode: 500,
            message: "Internal Server Error",
            details: e.toString()
        };
        return response.status(500).json(commonError);
    }
};

通过浏览器请求 enter image description here 通过邮递员请求

enter image description here

我已经尝试过的东西

<块引用>
  1. 不同浏览器(Chrome、Firefox、Opera 和 MS Edge)最新版本
  2. 不同的节点版本(15.11.0、12.13.0 和 10.18.0)
  3. 不同的 momgo 数据库版本(4.4.4 和 4.2.11)
  4. 不同的猫鼬版本(5.11.19 和 5.10.0)
  5. 我尝试通过 sudo chmod -R 777 /project-folder 将项目文件夹权限设置为 777
  6. 我还尝试通过 chown 将用户所有权更改为项目文件夹
  7. 我已尝试验证请求正文数据并检查其类型,然后再将它们输入到 mongoose model.findOne() 函数中。
  8. Finlay,我尝试直接对 mongo shell 运行相同的查询,该 shell 以相应的文档而不是 null 进行响应。

我发现问题出在猫鼬查询上,但我无法 解决它。

预期行为

<块引用>

Mongoose 查询正常工作(找到已经在 数据库)。

回答1