简体   繁体   中英

How to post an array to Express API

I'm creating APIs with Express.js and SQL Server. I been posting an object which is easy and very simple, but now i have a new question: how to post an array?

Let's say i have a table which stores only two params:

Table_A
Id | CouponId

In fact, the only record that stores is CouponId , 'cause the Id is created by SQL Server on every record. So, the case is that i get a list of coupons from an api, and the idea is select from one to 'n' with a checkbox and save the selection.

This my code so far:

    function getList(){
      $http.get('/api/coupons')
      .then(function(data){
            $scope.infoCoupons = data.data.Response;
    }

On the HTML view:

<div class="col-lg-12" align="center">
                <input type="checkbox" ng-click="selectAll()"/> <a style="font-size:17px;color:black;text-decoration:none;">Select all coupons</a>
                <ul class="coupon-list">
                    <li ng-repeat="coupon in infoCoupons">
                        <input type="checkbox" ng-model="coupon.Select" ng-click="checked"/> <a style="font-size:17px;color:black;text-decoration:none;">{{coupon.CodeCoupon}}</a>
                    </li>
                </ul>
            </div>

Then, to get the selected coupons:

$scope.selectAll = function(){
    $scope.all = !$scope.all;
    $scope.infoCoupons.forEach(function(o){
        o.Select = $scope.all;
    });
}

function chosenCoupons(){
    var result = new Array();
    var checked = 0;

    $scope.infoCoupons.forEach(function(e){
        if(e.Select === true){
            result.push(e.Id);
            checked +=1;
        }
    });
    if($scope.all || checked > 0){
        alert("Selected coupons!");
    }
    else if(checked === 0){
        alert("Select at least one coupon");
    }
}

Then, my code for the API:

const express = require('express');
const bodyParser = require('body-parser');
const sql = require('mssql');
const app = express();

app.use(bodyParser.json());

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
    next();
});

const dbConfig = {
    user: "daUser",
    password: "daPass",
    server: "daServa",
    database: "daDB"
};

const executeQuery = function (res, query, parameters) {
    sql.connect(dbConfig, function (err) {
        if (err) {
            console.log(`There's an error: ${err}`);
            res.send(err);
            sql.close();
        }
        else {
            var request = new sql.Request();

            if (parameters && parameters.length > 0) {
                parameters.forEach(function (p) {
                    request.input(p.name, p.sqltype, p.value);
                });
            }


            request.query(query, function (err, result) {
                if (err) {
                    console.log(`Theres an error: ${err}`);
                    res.send(err);
                    sql.close();
                }
                else {
                    res.send(result);
                    sql.close();
                }
            });
        }
    });
}

app.post("/api/testApi", function(req, res){
    parameters = [
        { name: 'CouponId', sqltype: sql.VarChar, value: req.body.CouponId }
    ];

    var query = "INSERT INTO [Table_A] VALUES(@CouponId)";
    executeQuery(res, query, parameters);
});

const PORT = process.env.PORT || 8080

app.listen(PORT, () => {
    console.log(`App running on port ${PORT}`)
});

This is the code that usually works for an object. My question is: how can i send result (where result is the obtained array) on the API. I need to change something on my code on parameters ?

Hope you can help me. I'm using Javascript, Node, Express and SQL Server.

How to post an array to Express API

In angular you simply do $http.post(url, data) .

If you assign data to an object that has an array, it will reach express.
Then express can parse the body since you have app.use(express.bodyParser()); so the object should be available to you on the body.

URL Query Params

If you are trying to use query parameters, to pass an array, lets say on attribute items so you simply declare it multiple times

items=1&items=2&items=3 should be parsed to req.query.items === [1,2,3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM