首页 文章

使用SQL Server设置节点/ express rest api

提问于
浏览
-1

我试图用SQL Server设置nodejs rest api . 我设法使我的GET方法起作用,但PUT根本没有响应 . 我用邮递员这样调用PUT方法:http://localhost:8080/api/user/1?firstname=John . 我做错了什么?

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 回答

  • 0

    您的请求处理程序处理请求的主体 .

    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);
    });
    

    为了使您的请求工作,您需要提供包含JSON正文的正确PUT请求 . 卷曲版本看起来像:

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

相关问题