The Response from NodeJS has an offset of 1. E.g: 1 Query: A Output: Empty Response 2 Query: B Output: A 3 Query: C Output: B
If you need API/JSON Output, let me know.
I feels like i am just having a logical problem here. Or is there a command for this offset?
const express = require('express');
// Constants
const PORT = 8080;
const HOST = '0.0.0.0';
var resultQueryFilter = "";
var search_param = "";
var Connection = require('tedious').Connection;
var config = {
server: '172.17.0.2',
authentication: {
type: 'default',
options: {
userName: 'sa',
password: 'PW'
}
},
options: {
encrypt: false,
useUTC: true,
database: 'Park'
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
if(err) {
console.log('Error: ', err)
} else {
console.log("Successful connection");
}
});
connection.connect();
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatementQuery() {
request = new Request("SELECT * from dbo.users WHERE first_name like '%" search_param "%' FOR JSON PATH;", function(err) {
if (err) {
console.log(err);}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
resultQueryFilter = column.value " ";
}
});
//console.log(resultQueryFilter);
});
connection.execSql(request);
}
const app = express();
app.get('/company/search', (req, res) => {
search_param = String(req.query.company_name);
if (!search_param) {
//No search param send
console.log("Search request ist empty. Returning HTTP-406");
res.status(406).send("Forbidden."); //Forbidden, as query cannot be empty
} else {
console.log("API Call with search req");
console.log("Going to execute query");
executeStatementQuery();
console.log("Executed Query");
console.log("Returning Output as JSON: " String(resultQueryFilter));
res.send(resultQueryFilter);
console.log("Clearing old params");
search_param = "";
resultQueryFilter = "";
console.log("Request done");
}
});
app.listen(PORT, HOST, () => {
console.log(`Running on http://${HOST}:${PORT}`);
});
cant post owtherwise: ererwearew rqe rwer fsfwe
CodePudding user response:
Your code uses global variables request
and resultQueryFilter
, which will be used concurrently by all the queries that you make. This cannot lead to correct (or even predictable) results.
Use local variables:
app.get('/company/search', function(req, res) {
var search_param = String(req.query.company_name);
var request = new Request("SELECT * from dbo.users WHERE first_name like '%" search_param "%' FOR JSON PATH;",
function(err) {
if (err) console.log(err);
});
var resultQueryFilter = "";
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
resultQueryFilter = column.value " ";
}
});
});
request.on('done', function() {
res.send(resultQueryFilter);
});
connection.execSql(request);
});