mongodb 如何修复nodejs中“cannot post error”?

wkftcu5l  于 2021-07-06  发布在  Go
关注(0)|答案(2)|浏览(135)

node.js新手我正在做一个nodejs-experss-mongodb项目,我目前正在实现一个订阅功能,具体要求如下:
方法:post
URL:localhost:8080/API/v1/users/:userid/subscribe/:businessid
AC:当前用户的关注数组,添加业务id。
将当前用户id添加到商家的关注者数组中
最后返回201,{user}
但是每次我尝试在postman中测试它时,我都会得到这个错误:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /api/v1/users/647965651bbc93663ec695d5/subscribe/647965651bbc93663ec695d6%0A</pre>
</body>
</html>

我不知道哪里出了问题。我的用户模型:

import { Request, Response } from 'express';
import UserModel from '../models/User';
import mongoose from 'mongoose';

export const subscribe = async (req: Request, res: Response) => {
  const { userid, businessid } = req.params;
  
  // search for student id
  const user = await UserModel.findById(userid).exec();
  // search for business id
  const business = await UserModel.findById(businessid).exec();

  if(!user || !business){
    res.status(404).json({ error: 'user or business not found' });
    return;
  }

  if (!user.is_business) {
    return res.status(403).json({ message: 'User is not a business' });
  }

  business.follower.addToSet(userid);
  await business.save();

  user.following.addToSet(businessid);
  await user.save();
  
  return res.status(201).json({ user });
};

用户模型:

import { Schema, model } from 'mongoose';
const schema: Schema = new Schema({

  is_business: {
    type: Boolean,
    required: true,
    default: false,
  },

  following:  [{
    type: Schema.Types.ObjectId,
    ref: "User",
  },],

  follower: [{
    type: Schema.Types.ObjectId,
    ref: "User",
  }],
},

{
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at',
  }
});
export default model('User', schema);

我的用户路由:

import { Router } from 'express';
import { index, deactivate, activate, subscribe } from '../../controllers/users';

const userRouter = Router();

userRouter.post('/users/subscribe/:userid/:businessid', subscribe);

export default userRouter;

有人知道怎么修吗?任何帮助是赞赏!

mgdq6dx1

mgdq6dx11#

您的路由定义为:

'/users/subscribe/:userid/:businessid'

但是,您的URL被发送为:

'/users/:userid/subscribe/:businessid'

这些不匹配。改变其中一个以匹配另一个。

swvgeqrz

swvgeqrz2#

请检查您重定向到的URL,我认为您已经写了这些

  • /API/v1/users/647965651bbc93663ec695d5/subscribe/647965651bbc93663ec695d6%0A
  • /API/v1/users/(subscribe_id)/647965651bbc93663ec695d5/:bussinessid

相关问题