export.create和router.post有什么区别?

时间:2019-02-19 22:17:55

标签: node.js express sequelize.js postman

我已经看到了两种创建静态API的方法。

1:“ export.create”,一旦在邮递员上添加代码,就必须以json格式添加它。

2:“ router.post”,我知道这是使用express的,当您在邮递员上添加代码时,可以使用“ x-www-form-urlencoded”添加它

有什么区别?

router.post("/", (req, res) => {
    if(!req.body.certifications,
       !req.body.memberships,
       !req.body.hobbies,
       !req.body.interests) {
        res.status(400)
        res.json({
            error: "Bad Data"
        })
    } else {
       Basic.create(req.body)
        .then(() => {
            res.send("Basic Added")
        })
        .catch(err => {
            res.send("Error: " + err)
        })
    }
})

------------------------------------------

exports.create = (req, res) => {
    var customer;
    Customer.create({
       firstname: req.body.firstname,
       lastname: req.body.lastname,
       age: req.body.age 
    }).then(createdCustomer => {
        // Send  Created Customer to client
        customer = createdCustomer;

        return Address.create({
           street: req.body.street,
           phone: req.body.phone
        })
    }).then(address => {
        customer.setAddress(address)
        res.send('OK'); 
    })
};

1 个答案:

答案 0 :(得分:3)

exports.create只是将方法导出为commonjs模块的一部分,然后可以与其他文件中的router.post一起使用。

类似这样的东西:

const { create } = require('./the_file_name.js');
router.post('/', create);