简体   繁体   English

如何将数组发布到Express API

[英]How to post an array to Express API

I'm creating APIs with Express.js and SQL Server. 我正在使用Express.js和SQL Server创建API。 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. 实际上,唯一存储的记录是CouponId ,因为该Id是由SQL Server在每条记录上创建的。 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. 因此,这种情况是,我从api获取了一张优惠券列表,其想法是使用复选框从一个到'n'进行选择并保存选择。

This my code so far: 到目前为止,这是我的代码:

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

On the HTML view: 在HTML视图上:

<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: 然后,我的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. 我的问题是:如何在API上发送result (结果是获得的数组)。 I need to change something on my code on parameters ? 我需要更改代码中的parameters吗?

Hope you can help me. 希望您能够帮助我。 I'm using Javascript, Node, Express and SQL Server. 我正在使用Javascript,Node,Express和SQL Server。

How to post an array to Express API 如何将数组发布到Express API

In angular you simply do $http.post(url, data) . 在angular中,您只需执行$http.post(url, data)

If you assign data to an object that has an array, it will reach express. 如果将数据分配给具有数组的对象,它将达到express。
Then express can parse the body since you have app.use(express.bodyParser()); 然后,express可以解析正文,因为您有app.use(express.bodyParser()); so the object should be available to you on the body. 因此该物体应该可以在身体上使用。

URL Query Params URL查询参数

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说几句,以便您多次声明它

items=1&items=2&items=3 should be parsed to req.query.items === [1,2,3] items=1&items=2&items=3应该解析为req.query.items === [1,2,3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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