使用SQL Server设置node/express rest api



我正在尝试用SQL Server设置一个nodejs rest api。我设法使GET方法工作,但PUT根本没有响应。我用poster调用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);
});

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

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

相关内容

  • 没有找到相关文章

最新更新