Express POST 不工作但 GET 和 PATCH 是
Express POST not working but GET and PATCH is
我正在尝试为我的项目创建一些 REST API,但我似乎无法 POST 工作。我已经在 Postman 中测试了 GET 和 PATCH,它们都工作正常。如有任何帮助,我们将不胜感激!
product.service.ts
export class ProductService {
constructor(private readonly model: Model<ProductType>) {}
public getProduct = async (id: string): Promise<ProductType | null> => {
return await this.model.findOne({ id });
};
public createProduct = async (
body: ProductType
): Promise<ProductType> => {
return await this.model.create(body);
};
}
export const productService = new ProductService(ProductModel);
product.controller.ts
export class productController {
constructor(private readonly service: ProductService) {}
public getProduct = async (req: Request, res: Response) => {
const response = await this.service.getProduct(req.params.id);
res.send(response);
};
public createProduct = async (req: Request, res: Response) => {
const response = await this.service.createProduct(req.body);
res.send(response);
};
}
export const productController = new ProductController(
productService
);
product.route.ts
const router: Router = express.Router();
router.get('/products/:id', productController.getProduct);
router.post('products/new', productController.createProduct); //this route returns a 404
export default router;
所以当我尝试在 Postman 中 post 它 returns 一个 404,但是 get 工作正常。感谢您的帮助!
正如在对原始 post 的评论中提到的,我在 post 路由 URL 中漏掉了正斜杠。
谢谢!
我正在尝试为我的项目创建一些 REST API,但我似乎无法 POST 工作。我已经在 Postman 中测试了 GET 和 PATCH,它们都工作正常。如有任何帮助,我们将不胜感激!
product.service.ts
export class ProductService {
constructor(private readonly model: Model<ProductType>) {}
public getProduct = async (id: string): Promise<ProductType | null> => {
return await this.model.findOne({ id });
};
public createProduct = async (
body: ProductType
): Promise<ProductType> => {
return await this.model.create(body);
};
}
export const productService = new ProductService(ProductModel);
product.controller.ts
export class productController {
constructor(private readonly service: ProductService) {}
public getProduct = async (req: Request, res: Response) => {
const response = await this.service.getProduct(req.params.id);
res.send(response);
};
public createProduct = async (req: Request, res: Response) => {
const response = await this.service.createProduct(req.body);
res.send(response);
};
}
export const productController = new ProductController(
productService
);
product.route.ts
const router: Router = express.Router();
router.get('/products/:id', productController.getProduct);
router.post('products/new', productController.createProduct); //this route returns a 404
export default router;
所以当我尝试在 Postman 中 post 它 returns 一个 404,但是 get 工作正常。感谢您的帮助!
正如在对原始 post 的评论中提到的,我在 post 路由 URL 中漏掉了正斜杠。
谢谢!