Home > Software engineering >  Trying to retrieve value from sql server and offer the user a text file download with the value
Trying to retrieve value from sql server and offer the user a text file download with the value

Time:07-09

I am getting a value from SQL Server. After that I try to offer a text file download to the user with the content being the value I retrieve from the database. Through a query string I pass the ID value (http://localhost:8080/index.js?ID=1).

Setting the text variable at the bottom with the database value is not possible. How can I export the database value to text file in this scenario?

const http = require('http');
const url = require('url');
const sql = require('mssql');

// config info database
const config = {
    user:       'test_user',
    password:   '123',
    server:     'localhost',
    database:   'TestDatabase',
    port:       1433,
    trustServerCertificate: true,
};

http.createServer(function (req, res) {
    const queryObject = url.parse(req.url, true).query.ID;

    // connect to database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create a new Request object
        let sqlRequest = new sql.Request();

        // query the database and get data in the data Object
        let sqlQuery='SELECT Testvalue FROM TestDatabase.dbo.TestTable WHERE ID = '   queryObject;
        sqlRequest.query(sqlQuery, function (err, data) {

            if (err) console.log(err)

            // display the data in the console
            //console.table(data.recordset[0].Testvalue);
            text = "This is a content of a txt file. Value from database = "   data.recordset[0].Testvalue;

            // close the connection
            sql.close();

        });
    });

    text = 'how do I get the value in here from the database??';
    res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':'attachment; filename=file.txt'});
    res.end(text);

}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

CodePudding user response:

Looks to me like you just have to move your res.writeHead... and res.end... into the code block where you get the text from the database - try just after sql.close();

That's assuming your sql works.

  • Related