1
votes

I am trying to write data to MS SQL server when an API POST is hit with JSON Data.

var express = require('express');
var app = express();
var sql = require('mssql');

// Connection string parameters.
var sqlConfig = {
    user: 'sa',
    password: 'Forward@123',
    server: '115.187.45.88',
    database: 'Example',
    requestTimeout: 1000,
    options: {
      "encrypt": false,
      "enableArithAbort": true
  }
}

// Start server and listen on http://localhost:8080/
var server = app.listen(8080, function () {
    var host = server.address().address
    var port = server.address().port

    console.log("app listening at http://%s:%s/SendData", host, port)
});

app.use(
    express.urlencoded({
      extended: true
    })
  )
  
app.use(express.json())

app.post('/SendData', function (req, res) {

let data = '';
  req.on('data', chunk => {
    data += chunk;
  })
  
  req.on('end', () => {
    var obj=JSON.parse(data);
    for(var i=0;i<obj.length;i++){
        console.log(obj[i]);

        //write in db

        var sqlString="INSERT INTO [dbo].[EmpTable] ([id],[fname],[lname]) VALUES ("+obj[i].id+",'"+obj[i].fname+"','"+obj[i].lname+"')";
        console.log("sqlString ----- "+sqlString);
        executeQuery(res, sqlString);

    }
  })
    res.setHeader('Access-Control-Allow-Origin', '*');  
    return res.status(200).json({"Message":"Success!!!"});
    
});





var executeQuery = function(res,query){
    sql.connect(sqlConfig,function(err){
        if(err){
            console.log("there is a database connection error -> "+err);
            res.send(err);
        }
        else{
            // create request object
            var request = new sql.Request();

            // query to the database
            request.query(query,function(err,result){
                if(err){
                    console.log("error while querying database -> "+err);
                    res.send(err);
                }
                else{
                    res.send(result);
                    sql.close();
                }
            });
        }
    });
}

I am getting the following error :

_http_outgoing.js:491 throw new Error('Can't set headers after they are sent.');

Error: Can't set headers after they are sent. at validateHeader (_http_outgoing.js:491:11) at ServerResponse.setHeader (_http_outgoing.js:498:3) at ServerResponse.header (E:\Node Workspace\node-post-api\node_modules\express\lib\response.js:771:10) at ServerResponse.send (E:\Node Workspace\node-post-api\node_modules\express\lib\response.js:170:12) at ServerResponse.json (E:\Node Workspace\node-post-api\node_modules\express\lib\response.js:267:15) at ServerResponse.send (E:\Node Workspace\node-post-api\node_modules\express\lib\response.js:158:21) at E:\Node Workspace\node-post-api\post-api-db-write.js:80:25 at _query (E:\Node Workspace\node-post-api\node_modules\mssql\lib\base\request.js:420:9) at Request.tds.Request.err [as userCallback] (E:\Node Workspace\node-post-api\node_modules\mssql\lib\tedious\request.js:479:15) at Request.callback (E:\Node Workspace\node-post-api\node_modules\tedious\lib\request.js:56:14)

1

1 Answers

0
votes

When a message is posted to /SendData you say:

res.setHeader('Access-Control-Allow-Origin', '*');  
return res.status(200).json({"Message":"Success!!!"});

This sends the one and only response that you can make to the request.

You also call executeQuery(res, sqlString) in which you:

res.send(result);

That also sends the one and only response that you can make to the request.