POST在Express API上后返回插入的ID

时间:2019-01-03 03:18:03

标签: javascript node.js sql-server express

我正在与Express和SQL Server一起创建mi API。现在,我需要在POST之后返回API响应上插入的ID。

到目前为止,这是我的代码:

    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: "usr",
    password: "psswd",
    server: "server",
    database: "daDB"
};

const executeQuery = function (res, query, parameters) {
    sql.connect(dbConfig, function (err) {
        if (err) {
            console.log(`You have 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(`You have an error: ${err}`);
                    res.send(err);
                    sql.close();
                }
                else {
                    res.send(result.recordset);
                    sql.close();
                }
            });
        }
    });
}

app.get("/api/InvoiceRequestApi", function (req, res) {

    var query = "SELECT * FROM [InvoiceRequest];
    executeQuery(res, query);
});

app.post("/api/InvoiceRequestApi", function (req, res) {
    const parameters = [
        { name: 'OrderId', sqltype: sql.VarChar, value: req.body.OrderId },
        { name: 'Mail', sqltype: sql.VarChar, value: req.body.Mail },
        { name: 'Name', sqltype: sql.VarChar, value: req.body.Name },
        { name: 'RFC', sqltype: sql.VarChar, value: req.body.RFC },
        { name: 'Adress', sqltype: sql.VarChar, value: req.body.Adress },
        { name: 'NoExt', sqltype: sql.VarChar, value: req.body.NoExt },
        { name: 'NoInt', sqltype: sql.VarChar, value: req.body.NoInt },
        { name: 'District', sqltype: sql.VarChar, value: req.body.District },
        { name: 'CP', sqltype: sql.VarChar, value: req.body.CP },
        { name: 'Municipality', sqltype: sql.VarChar, value: req.body.Municipality },
        { name: 'State', sqltype: sql.VarChar, value: req.body.State },
        { name: 'CreationDate', sqltype: sql.VarChar, value: req.body.CreationDate },
        { name: 'GeneratedInvoice', sqltype: sql.Bit, value: req.body.GeneratedInvoice },
        { name: 'InvoiceFile', sqltype: sql.VarChar, value: req.body.InvoiceFile },
        { name: 'FileXml', sqltype: sql.VarChar, value: req.body.FileXml },
        { name: 'StatusId', sqltype: sql.Int, value: req.body.StatusId }
    ];

    var query = "INSERT INTO [InvoiceRequest] VALUES(@OrderId, @Mail, @Name, @RFC, @Adress, @NoExt, @NoInt, @District, @CP, @Municipality, @State, @CreationDate, @GeneratedInvoice, @InvoiceFile, @FileXml, @StatusId) SELECT SCOPE_IDENTITY() AS Id";
    executeQuery(res, query, parameters);
});        

const PORT = process.env.PORT || 8080

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

我发现了一些关于stackoverflow的帖子,其中建议在插入后使用SELECT SCOPE_IDENTITY() AS Id,其他地方在插入之前也使用OUTPUT INSERTED.Id,但是在两个答案中我都有两个错误。如果我这样发送数据:

function sendMyData(){
        var invoiceData = {
            OrderId: $scope.theOrder,
            Mail: $scope.getMail,
            Name: $scope.getName,
            RFC: $scope.getTax,
            Adress: $scope.getStreet,
            NoExt: $scope.getExternal,
            NoInt: $scope.getInternal,
            District: $scope.getDistrict,
            CP: $scope.getPostalCode,
            Municipality: $scope.getMunicipality,
            State: $scope.getState,
            CreationDate: '2019-01-02',
            GeneratedInvoice: null,
            InvoiceFile: null,
            FileXml: null,
            StatusId: 1
        };
        //console.log(invoiceData);
        saveRequest.save(invoiceData).$promise
        .then(function(response){
            console.log(response);
        });
    }

该错误表明:

  

操作save的资源配置错误。预期响应包含一个对象但得到一个数组

因此,如果我进行如下更改:

function sendMyData(){
        var invoiceData = {
            OrderId: $scope.theOrder,
            Mail: $scope.getMail,
            Name: $scope.getName,
            RFC: $scope.getTax,
            Adress: $scope.getStreet,
            NoExt: $scope.getExternal,
            NoInt: $scope.getInternal,
            District: $scope.getDistrict,
            CP: $scope.getPostalCode,
            Municipality: $scope.getMunicipality,
            State: $scope.getState,
            CreationDate: '2019-01-02',
            GeneratedInvoice: null,
            InvoiceFile: null,
            FileXml: null,
            StatusId: 1
        };
        //console.log(invoiceData);
        saveRequest.save([invoiceData]).$promise
        .then(function(response){
            console.log(response);
        });
    }

该错误表明:

  

“无法将值NULL插入表'daDB.dbo.InvoiceRequest'的列'OrderId'中;该列不允许为空。插入失败。”

我在做什么错?有人可以帮我吗?

更新

使用没有找到两个示例的POST方法,该过程成功;换句话说,POST可以工作。

还有一个小问题:

我可以在var查询getdate()上使用它来设置我的CreationDate吗?

我正在使用Javascript,Node,Express和SQL Server。

0 个答案:

没有答案