Setting a node/express rest api with SQL Server

1.3k Views Asked by At

I am trying to set a nodejs rest api with SQL Server. I managed to make my GET method to work, but the PUT doesn't respond at all. I call the PUT method with postman like this: http://localhost:8080/api/user/1?firstname=John. What I am doing wrong?

var express = require("express");
var bodyParser = require("body-parser");
var sql = require("mssql");
var app = express(); 


// Body Parser Middleware
app.use(bodyParser.json()); 

// CORS Middleware
app.use(function (req, res, next) {
    // Enabling CORS 
    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();
});

// Setting up server
var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
 });

// Initiallising connection string
var dbConfig = { ... };

//Function to connect to database and execute query
var executeQuery = function(res, query) {
    new sql.ConnectionPool(dbConfig).connect().then(pool => {
        return pool.request().query(query)
    }).then(result => {
        let rows = result.recordset
        res.setHeader('Access-Control-Allow-Origin', '*')
        res.status(200).json(rows);
        sql.close();
    }).catch(err => {
        res.status(500).send({ message: "${err}"})
        sql.close();
    });
}

// GET API
app.get("/api/user/:id", function(req , res, next) {
    var query = "Select * from TestTable where id= " + req.params.id;
    executeQuery (res, query);
});

// PUT API
app.put("/api/user/:id", function(req , res, next) {
    var query = "UPDATE TestTable SET firstname= " + req.body.firstname  +  "   WHERE Id= " + req.params.id;
    executeQuery (res, query);
});
1

There are 1 best solutions below

0
On

Your request handler handles the body of the request.

app.put("/api/user/:id", function(req , res, next){
     // req.body is the body of the request
     // req.query is the query parameters in the URL ( like ?firstname=1 )
     var query = "UPDATE TestTable SET firstname= " + req.body.firstname  +  "   WHERE Id= " + req.params.id;
     executeQuery (res, query);
});

In order for your request to work you need to provide a proper PUT request containing JSON body. A curl version would look like :

curl -H 'Content-Type: application/json' \
     -X PUT \
     -d '{"firstname": "John"}' \ 
     http://localhost:8080/api/user/1