0

我正在尝试使用 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);
});
4

1 回答 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
于 2018-12-09T21:04:05.553 回答