很適合製作API和NodeJS應用程序。我已經有2路NodeJS API文件夾設置
一個server.js文件app.get("/api/allinfo", function (req, res) {
code...
}
app.get("/api/geo", function (req, res) {
more code..
}
當前文件夾結構
|-- node_modules
|-- server.js
|--package.json
的server.js文件中有它的一切
//Initiallising node modules
var express = require("express");
var bodyParser = require("body-parser");
var sql = require("mssql");
var app = express();
// Setting Base directory
app.use(bodyParser.json());
//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 = {
user: "XXX",
password: "XXX",
server: "XXX",
database: "XXX"
};
//API'S
//Get all the information we have about an address
app.get("/api/allinfo", function (req, res) {
var query ='Select * from TABLE';
executeQuery(res, query);
});
//Function to connect to database and execute query
var executeQuery = function (res, query) {
sql.connect(dbConfig, function (err) {
if (err)
console.log("Error while connecting database :- " + 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)
}
});
}
});
}
如何重新排列這成一個適當的文件夾結構? 我需要對代碼進行哪些調整才能發生?
https://www.tutorialspoint.com/nodejs/nodejs_restful_api.htm –