У меня была проблема с отправкой на API, созданный с помощью Express.js и БД SQL Server, пока не нашел следующее решение:
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: "daServer",
database: "daDB"
};
const executeQuery = function (res, query, parameters) {
sql.connect(dbConfig, function (err) {
if (err) {
console.log(err);
res.send(err);
}
else {
var request = new sql.Request();
parameters.forEach(function (p) {
request.input(p.name, p.sqltype, p.value);
});
request.query(query, function (err, result) {
if (err) {
console.log(err);
res.send(err);
sql.close();
}
else {
res.send(result.recordsets);
sql.close();
}
});
}
});
}
//GET ALL
app.get("/api/InvoiceRequestTaxes", function (req, res) {
var query = "SELECT * FROM [InvoiceRequestTaxes]";
executeQuery(res, query);
});
//GET BY InvoiceRequestId
app.get("/api/InvoiceRequestTaxes/:idRequest", function (req, res) {
const requestId = req.params.idRequest;
var query = "SELECT * FROM [InvoiceRequestTaxes] WHERE InvoiceRequestId=" + requestId;
executeQuery(res, query);
});
//POST
app.post("/api/InvoiceRequestTaxes", function (req, res) {
const parameters = [
{ name: 'InvoiceRequestId', sqltype: sql.Int, value: req.body.InvoiceRequestId },
{ name: 'IdProduct', sqltype: sql.Int, value: req.body.IdProduct },
{ name: 'Price', sqltype: sql.Money, value: req.body.Price },
{ name: 'Cost', sqltype: sql.Money, value: req.body.Cost },
{ name: 'Margin', sqltype: sql.Money, value: req.body.Margin },
{ name: 'BaseMarginIVA', sqltype: sql.Money, value: req.body.BaseMarginIVA },
{ name: 'BaseCostIVA', sqltype: sql.Money, value: req.body.BaseCostIVA },
{ name: 'IVA', sqltype: sql.Money, value: req.body.IVA },
{ name: 'StatusId', sqltype: sql.Int, value: req.body.StatusId },
{ name: 'DateCreated', sqltype: sql.VarChar, value: req.body.DateCreated },
{ name: 'DateUpdated', sqltype: sql.VarChar, value: req.body.DateUpdated }
];
var query = "INSERT INTO [InvoiceRequestTaxes](InvoiceRequestId, IdProduct, Price, Cost, Margin, BaseMarginIVA, BaseCostIVA, IVA, StatusId, DateCreated, DateUpdated) VALUES(@InvoiceRequestId, @IdProduct, @Price, @Cost, @Margin, @BaseMarginIVA, @BaseCostIVA, @IVA, @StatusId, @DateCreated, @DateUpdated)";
executeQuery(res, query, parameters);
});
const PORT = process.env.PORT || 8080
app.listen(PORT, () => {
console.log(`App running on port: ${PORT}`)
});
Как видите, я должен объявить на const executeQuery
параметры.Моя проблема возникает, когда я пытаюсь получить, потому что консоль показывает следующее сообщение:
Невозможно прочитать свойство 'forEach' из неопределенного
Как я могусделать метод get, пока я не отправляю никаких параметров?
Я пытался передать параметры только в сообщении, например так:
app.post("/api/InvoiceRequestTaxes", function (req, res, parameters) {
const parameters = [
{ name: 'InvoiceRequestId', sqltype: sql.Int, value: req.body.InvoiceRequestId },
{ name: 'IdProduct', sqltype: sql.Int, value: req.body.IdProduct },
{ name: 'Price', sqltype: sql.Money, value: req.body.Price },
{ name: 'Cost', sqltype: sql.Money, value: req.body.Cost },
{ name: 'Margin', sqltype: sql.Money, value: req.body.Margin },
{ name: 'BaseMarginIVA', sqltype: sql.Money, value: req.body.BaseMarginIVA },
{ name: 'BaseCostIVA', sqltype: sql.Money, value: req.body.BaseCostIVA },
{ name: 'IVA', sqltype: sql.Money, value: req.body.IVA },
{ name: 'StatusId', sqltype: sql.Int, value: req.body.StatusId },
{ name: 'DateCreated', sqltype: sql.VarChar, value: req.body.DateCreated },
{ name: 'DateUpdated', sqltype: sql.VarChar, value: req.body.DateUpdated }
];
parameters.forEach(function (p) {
request.input(p.name, p.sqltype, p.value);
});
var query = "INSERT INTO [InvoiceRequestTaxes](InvoiceRequestId, IdProduct, Price, Cost, Margin, BaseMarginIVA, BaseCostIVA, IVA, StatusId, DateCreated, DateUpdated) VALUES(@InvoiceRequestId, @IdProduct, @Price, @Cost, @Margin, @BaseMarginIVA, @BaseCostIVA, @IVA, @StatusId, @DateCreated, @DateUpdated)";
executeQuery(res, query, parameters);
});
Но теперь я получаю еще одну ошибку на консоли:
request.input не является функцией
Надеюсь, кто-нибудь может мне помочь.
Я использую Express.js, Node и SQL Server.