提问人:Thalia 提问时间:11/7/2023 最后编辑:VLAZThalia 更新时间:11/7/2023 访问量:24
postman 上的 post API 请求出现意外错误
post API request on postman is giving unexpected error
问:
当我尝试 post 方法在 postman 中添加供应商并正确编写所有参数时,它说“错误”:“错误,供应商未添加。
但是当我错误地添加其中一个参数时,它会从验证器返回错误(这很好)。我只是不明白为什么正确的参数仍然给出错误。它在我的命令提示符上说:“绑定参数不得包含未定义。要传递 SQL NULL,请指定 JS null”
我编写了一个服务文件,其中包含 post 方法的 sql 查询、需要快速验证器在执行 sql 查询之前验证输入数据的控制器文件,以及用于为供应商实体配置路由的 routes 文件。
我找不到我的代码有什么问题。我希望有人能帮助我理解为什么会发生这种情况。这是我的代码:
//supplierRoutes.js
const express = require('express');
const { getAllSuppliersController, addSupplierController, updateSupplierController, deleteSupplierController, getSupplierByIdController } = require('../controllers/supplierController');
const { addSupplierValidation, updateSupplierValidation } = require('../validations/supplierValidator');
const router = express.Router();
router.get('/', getAllSuppliersController);
router.get('/', getSupplierByIdController);
router.post('/addSupplier', addSupplierValidation, addSupplierController);
router.put('/', updateSupplierValidation, updateSupplierController);
router.delete('/', deleteSupplierController);
module.exports = router;
//supplierServices.js
const { query } = require("../database/db");
const addSupplier = async (SupplierName, PhoneNumber, Email) => {
try {
let sql = `INSERT INTO supplier
(SupplierName, PhoneNumber, Email)
VALUES (?, ?, ?);`;
const result = await query(sql,
[
SupplierName,
PhoneNumber,
Email
]);
let addedSupplier = await query(`select * from supplier where SupplierID = ?;`, [result?.SupplierID]);
return addedSupplier;
} catch (err) {
throw new Error('Failed to add supplier.');
}
}
//supplierController.js
const { validationResult } = require("express-validator");
const { getSuppliers, addSupplier, updateSupplier, deleteSupplier } = require("../services/supplierService")
const addSupplierController = async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { SupplierName, PhoneNumber, Email } = req.body;
try {
const response = await addSupplier( SupplierName, PhoneNumber, Email);
res.status(201).json({ response });
} catch (error) {
res.status(500).json({ error: "Error, supplier wasn't added." });
}
}
答: 暂无答案
评论