【问题标题】:In expressjs application how to handle array with POST request in API endpoint?在 expressjs 应用程序中,如何在 API 端点中处理带有 POST 请求的数组?
【发布时间】:2021-03-04 16:42:50
【问题描述】:

我正在尝试构建 expressjs API 端点。对于我的应用程序目的,对象将来到另一台服务器,它是多个对象。我需要将其转换为数组,然后将其推送到我的数据库或其他人。

我使用的是 express 4+,所以我没有使用 body-parser,因为它包含在 express 中。

###注意:数据来自另一台服务器,格式为“application/x-www-form-urlencoded”。

我希望数据会是这样的静态数据:

    [
        {
            "name": "As Md Habibullah",
            "phone": "+457578424",
            "email": "fhhgssa@yahoo.com",
            "car_brand": "Mercedes-Benz",
            "car_number": "256858"
        },
        {
            "name": "Filippo Masiero",
            "phone": "+hgfhfhfg",
            "email": "ghjhghjhg@yahoo.com",
            "car_brand": "Mercedes-Benz",
            "car_number": "25586458"
        },
        {
            "name": "Azad Ahmed",
            "phone": "+ghjggffg",
            "email": "jghjh@yahoo.com",
            "car_brand": "Mercedes-Benz",
            "car_number": "2566868"
        },
        {
            "name": "Md Musa",
            "phone": "+fgjhfgjfh",
            "email": "dfgyfyhfggh@yahoo.com",
            "car_brand": "Mercedes-Benz",
            "car_number": "256858"
        }
    ]

我假设数据会到达我的端点,它是多个对象,我需要像多个对象一样做一个数组:{}, {}, {}

我想做一个数组,比如:[{}, {}, {}, {}]

有可能吗?

【问题讨论】:

    标签: javascript arrays api express rest


    【解决方案1】:

    如果数据以 JSON 形式出现,但包含在 application/x-www-form-urlencoded 内容类型中,那么您将不得不为该内容类型使用 express 中间件。这将使您将 JSON 解码为纯文本,然后您必须手动将其解析为 Javascript 对象,如下所示:

    // middleware for parsing application/x-www-form-urlencoded content-type 
    app.use(express.urlencoded({extended: true}));
    
    app.post("/somerouter", (res, res) => {
        try {
            // parse decoded body text from JSON into Javascript object
            let obj = JSON.parse(req.body);
            console.log(obj);
            // process obj here
            res.send("ok");
        } catch(e) {
           console.log("bad JSON", e);
           res.sendStatus(400);
        }
    });
    

    理想情况下,请求将以application/json 发送,然后您可以使用express.json() 中间件,JSON 将自动解析到您的对象中。


    但是,如果您的 application/x-www-form-urlencoded 数据只是表单数据,那么它已经为您解析并且已经在 req.body 作为该对象的属性。直接在req.body访问即可:

    // middleware for parsing application/x-www-form-urlencoded content-type 
    app.use(express.urlencoded({extended: true}));
    
    app.post("/somerouter", (res, res) => {
        console.log(req.body);
        // process data in req.body and then send some response
        res.send("ok");
    });
    

    【讨论】:

    • 谢谢,其实我正在使用 app.use(express.urlencoded({extended: true}));但我想念这里的 try and catch 块。
    • 它不工作。 --------------------- bad JSON SyntaxError: Unexpected token o in JSON at position 1
    • @AsMdHabibullah - 那么客户端没有在该 application/x-www-form-urlencoded 编码正文中发送有效的 JSON。除非您确切地向我们展示客户发送的内容,否则我们无法提供进一步的帮助。在我显示的代码中,console.log(req.body) 显示了什么?
    • 嗯,显然这不是 JSON(这不是我从你的问题中想到的),它只是常规表单数据。如果你按照我的要求做了console.log(req.body),你会看到你有什么。即使不使用JSON.parse(),数据也已经存在。这就是你得到的。
    • { first_name: '', phone: '', MODELLO: '', TARGA: '', template: 'Gentile {{first_name}}, le ricordiamo che nel mese di maggio è previsto il tagliando年度 della sua {{MODELLO_2}} targata {{TARGA_2}} che potrà effettuare presso la nostra sede previo appuntamento。 Può prenotare anche online cliccando sul link internazionaleauto.com/officina-autorizzata Cordiali Saluti Internazionaleauto Team' }
    猜你喜欢
    • 1970-01-01
    • 2018-04-09
    • 2020-10-09
    • 2014-05-06
    • 2013-06-19
    • 2015-08-30
    • 1970-01-01
    • 2018-05-12
    • 2019-09-17
    相关资源
    最近更新 更多