Tạo một restful api với nodejs,express,mssql

Trong bài này mình sẽ hướng dẫn tạo một restful api đơn giản với nodejs và sqlserver. Đầu tiên ta chuẩn bị một database cho demo, cụ thể trong bài này mình sẽ tạo một database tên demo_restfull_api gồm 1 bảng posts

CREATE DATABASE [demo_restfull_api]
USE [demo_restfull_api]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[posts](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](200) NULL,
	[Content] [nvarchar](300) NULL,
 CONSTRAINT [PK_posts] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET IDENTITY_INSERT [dbo].[posts] ON 

INSERT [dbo].[posts] ([ID], [Title], [Content]) VALUES (1, N'restfull api ', N'tạo restful api')
INSERT [dbo].[posts] ([ID], [Title], [Content]) VALUES (2, N'nodejs', N'nodejs là gì')
SET IDENTITY_INSERT [dbo].[posts] OFF
USE [master]
GO

Mở command promt và cd đến thư mục gốc của project Tại command promt gõ

npm init

Sau đó điền các thông tin khởi tạo của project theo ý của bạn, ví dụ:

package name: (nodejsresfulsample) restful-api
version: (1.0.0)
description: restful api voi nodejs express mssql
entry point: (index.js)
test command:
git repository:
keywords:
author: luan
license: (ISC)
About to write to C:\Project\NodejsResfulsample\package.json:

{
  "name": "restful-api",
  "version": "1.0.0",
  "description": "restful api voi nodejs express mssql",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "luan",
  "license": "ISC"
}

Tiếp theo ta cài đặt các package cần thiết

npm install express --save
npm install mssql --save
npm install body-parser --save