// npm install express --save
// npm install mssql --save
// npm install -g nodemon
// nodemon app.js
var express = require('express');
var sql = require('mssql');
var app = express();
app.use(express.json()); // parse json body
var _PROTOCOL = 'HTTP';
var _SERVER = 'localhost';
var _PORT = 4444;
var _DEFAULTPORT = 9000;
// config for database
var config = {
user: '****',
password: '****',
server: 'localhost',
database: 'mosis_portal',
stream: false,
options: {
trustedConnection: true,
encrypt: true,
enableArithAbort: true,
trustServerCertificate: true, // incase recieve error: self signed certificate
}
};
app.get('/posts', function(req, res) {
sql.connect(config, function(err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('select * from posts').then(recordset => {
console.log(recordset.recordsets);
res.status(200).send(recordset.recordsets);
});
});
});
app.get('/post/:id', function (req, res) {
var id = req.params.id;
sql.connect(config, function(err, result, fields) {
if (err) console.log(err);
var request = new sql.Request();
request.query(`select * from posts where id= ${id}`).then(recordset => {
res.status(200).send(recordset.recordsets.pop().pop());
});
});
});
app.get('/title/:id', function (req, res) {
var id = req.params.id;
sql.connect(config, function(err, result, fields) {
if (err) console.log(err);
var request = new sql.Request();
request.query(`select top 1 * from posts where id= ${id}`).then(recordset => {
var info = recordset.recordsets.pop().pop();
var title = info.post_title;
var id = info.id;
console.log(info.id)
res.status(200).send(`<h1 onclick="location.href='http://localhost:4444/post/${id}'">${title}</h1>`);
});
});
});
app.listen(_PORT || _DEFAULTPORT, function() {
console.log(`\n\nServer running: ${_PROTOCOL}://${_SERVER}:${_PORT || _DEFAULTPORT}`);
});
No comments:
Post a Comment