Hướng dẫn can javascript use api? - javascript có thể sử dụng api?

Chuyển đến nội dung chính

Trình duyệt này không còn được hỗ trợ nữa.

Hãy nâng cấp lên Microsoft Edge để tận dụng các tính năng mới nhất, bản cập nhật bảo mật và hỗ trợ kỹ thuật.

Word JavaScript API overview

  • Bài viết
  • 06/21/2022
  • 2 phút để đọc

Trong bài viết này

An Word add-in interacts with objects in Word by using the Office JavaScript API, which includes two JavaScript object models:

  • Word JavaScript API: These are the application-specific APIs for Word. Introduced with Office 2016, the Word JavaScript API provides strongly-typed objects that you can use to access objects and metadata in a Word document.: These are the application-specific APIs for Word. Introduced with Office 2016, the Word JavaScript API provides strongly-typed objects that you can use to access objects and metadata in a Word document.

  • Common APIs: Introduced with Office 2013, the Common API can be used to access features such as UI, dialogs, and client settings that are common across multiple types of Office applications.: Introduced with Office 2013, the Common API can be used to access features such as UI, dialogs, and client settings that are common across multiple types of Office applications.

This section of the documentation focuses on the Word JavaScript API, which you'll use to develop the majority of functionality in add-ins that target Word on the web or Word 2016 or later. For information about the Common API, see Common JavaScript API object model.

Learn programming concepts

See Word JavaScript object model in Office Add-ins for information about important programming concepts.

Learn about API capabilities

Use other articles in this section of the documentation to learn how to get the whole document from an add-in, use search options in your Word add-in to find text, and more. See the table of contents for the complete list of available articles.

For hands-on experience using the Word JavaScript API to access objects in Word, complete the Word add-in tutorial.

For detailed information about the Word JavaScript API object model, see the Word JavaScript API reference documentation.

Try out code samples in Script Lab

Use Script Lab to get started quickly with a collection of built-in samples that show how to complete tasks with the API. You can run the samples in Script Lab to instantly see the result in the task pane or document, examine the samples to learn how the API works, and even use samples to prototype your own add-in.

See also

  • Word add-ins documentation
  • Word add-ins overview
  • Word JavaScript API reference
  • Office client application and platform availability for Office Add-ins

Phản hồi

Gửi và xem ý kiến phản hồi dành cho

Xin chào mọi người, hôm nay mình muốn demo cho những bạn chưa từng làm việc với ngôn ngữ Nodejs hoặc đơn giản là muốn tạo một RESTful API với NodeJS

Hướng dẫn can javascript use api? - javascript có thể sử dụng api?

REST là gì?

Đầu tiên thì các bạn cần hiểu rõ khái niệm về REST và RESTful là gì phải không?

REST là từ viết tắt của Representational State Transfer. Đó là kiến trúc tiêu chuẩn web và Giao thức HTTP.

Hiểu đơn giản thì các ứng dụng RESTful sử dụng các yêu cầu HTTP để thực hiện bốn hoạt động được gọi là CRUD (C: Create, R: Read, U: Update, và D: Delete).

Để hiểu rõ hơn về khái niệm RESTful các bạn có thể tham khảo bài viết này nhé: Tìm hiểu về RESTful web services

Trong hướng dẫn này, chúng ta sẽ tìm hiểu cách tạo một RESTful API bằng cách sử dụng Node.js.

Công cụ:

  • Node.js v7
  • MySQL
  • Trình soạn thảo văn bản hoặc IDE
  • Postman

Bắt đầu

** Giả định**: Máy bạn đã cài đặt NodeJS và MySQL

  • Đầu tiên bạn vào project tạo một tệp package.json -
    npm install express --save
    
    1

package.json là một tệp cung cấp thông tin cần thiết cho npm, cho phép nó xác định dự án cũng như xử lý các phụ thuộc của dự án.

npm install express --save
1 sẽ nhắc bạn nhập một số thông tin như tên ứng dụng, mô tả, phiên bản, tác giả, từ khóa,.... Khi tạo xong các bạn sẽ có 1 file package.json với nội dung như thế này:

{
  "name": "nodejs_api",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
  1. Tạo file server.js ở thư mục root. Trong file này, mình sẽ viết các giao thức để tạo một app mới.

  2. Tạo một thư mục có tên là api Bên trong thư mục này, mình tạo ra folder controllers để chứa các file controller, file routes.js để quản lý các link API và file db.js để kết nối database.

  3. Tạo ProductsController.js trong thư mục api/controllers

Cuối cùng thì project sẽ có cấu trúc như thế này:

Hướng dẫn can javascript use api? - javascript có thể sử dụng api?

Cài đặt server

  1. Ở đây mình dùng 4 package rất hay dùng đó là:
  • npm install express --save
    
    3 sẽ được sử dụng để tạo máy chủ
  • npm install express --save
    
    4 sẽ giúp mình theo dõi các thay đổi đối với ứng dụng của mình bằng cách xem các tệp đã thay đổi và tự động khởi động lại máy chủ.
  • npm install express --save
    
    5 để mình thêm các config cho database(host, port, user, pass, ...) và các config khác
  • npm install express --save
    
    6 để thao tác với database
npm install --save-dev nodemon
npm install express --save
npm install dotenv --save
npm install mysql --save

Khi cài đặt thành công, tệp package.json của bạn sẽ được sửa đổi để có 4 gói mới được cài đặt.

Mở file package.json và thêm script này vào mục scripts:

npm install express --save
7

Như vậy file package.json đã được thay đổi thành:

{
  "name": "nodejs_api",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^1.17.5"
  },
  "dependencies": {
    "express": "^4.16.3",
    "dotenv": "^5.0.1",
    "mysql": "^2.15.0"
  }
}
  1. Mở tệp server.js và nhập / sao chép mã bên dưới vào tệp
let express = require('express');
let app = express();
let port = process.env.PORT || 3000;

app.listen(port);

console.log('RESTful API server started on: ' + port);
  1. Trên terminal của bạn, tiếp tục chạy
    npm install express --save
    
    8 để bắt đầu máy chủ và sau đó bạn sẽ thấy
RESTful API server started on: 3000

Tạo database

CREATE DATABASE nodejs_api;

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `color` varchar(255) DEFAULT NULL,
  `price` decimal(10,0) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

INSERT INTO `products` VALUES ('1', 'Iphone X', 'Black', '30000000');
INSERT INTO `products` VALUES ('2', 'Samsung S9', 'White', '24000000');
INSERT INTO `products` VALUES ('3', 'Oppo F5', 'Red', '7000000');

Và đây là bảng sau khi chạy sql:

Hướng dẫn can javascript use api? - javascript có thể sử dụng api?

Tạo file kết nối Database

Trước tiên mình cần đưa các config cho database ra file .env Đây là file

npm install express --save
9 với nội dung:

DB_HOST="localhost"
DB_USER="root"
DB_PASS=""
DB_NAME="nodejs_api

** Lưu ý: ** Các bạn có thể tạo file .env.example để đưa lên git và đưa file .env vào .gitignore

Tiếp đến mình sẽ tạo file db.js:

npm install --save-dev nodemon
0

Như vậy là xong phần config db, khi sử dụng bạn chỉ cần require file db.js vào là có 1 đối tượng db để truy vấn db rồi.

Tạo routes

Dưới đây mình đã tạo hai router cơ bản (

npm install dotenv --save
0, và
npm install dotenv --save
1) với các phương thức

  • npm install dotenv --save
    
    0 có phương thức (
    npm install dotenv --save
    
    3 và
    npm install dotenv --save
    
    4)
  • npm install dotenv --save
    
    1 có 3 phương thức
    npm install dotenv --save
    
    3 ,
    npm install dotenv --save
    
    7 và
    npm install dotenv --save
    
    8. Như bạn có thể thấy, mình đã tạo 2 router và các phương thức để gọi các hàm xử lý tương ứng.

Và đây là nội dung file routes.js:

npm install --save-dev nodemon
1

Tiếp đến mình sẽ tạo file controller và các function tương ứng cho từng routes

Tạo file controller

Trong file ProductsController.js, mình sẽ tạo 5 function có tên: get, detai, update, store, delete và export 5 hàm này để sử dụng trong routes.js.

npm install --save-dev nodemon
2

Ở đây mình dùng package mysql, để tìm hiểu cách sử dụng chi tiết của package này bạn có thể truy cập vào:

Sắp xếp lại nội dung file server.js

Bên trên, mình đã có một đoạn code ngắn chỉ với mục đích tạo 1 server, sau khi tạo routes, controllers hoàn chỉnh mình sẽ sửa lại file server.js để có thể chạy được app hoàn chỉnh:

Dưới đây là file server.js:

npm install --save-dev nodemon
3

Mình đã cập nhật thêm

  • npm install dotenv --save
    
    9 để trích xuất toàn bộ phần nội dung của request đến và hiển thị nó trên đó
    npm install mysql --save
    
    0.
  • load dotenv để sử dụng environment variables
  • import file routes để load tất cả routes đã được khai báo trong file
  • thêm middleware để check nếu request API không tồn tại Dễ hiểu phải không nào??
    Hướng dẫn can javascript use api? - javascript có thể sử dụng api?

Kế tiếp để chạy lại server các bạn chạy lệnh:

npm install --save-dev nodemon
4

Và console sẽ hiển thị:

RESTful API server started on: 3000

Thực hiện test API trên Postman

  • Get all (method GET):
    npm install mysql --save
    
    1
npm install --save-dev nodemon
6
  • Get with id (method GET):
    npm install mysql --save
    
    2
npm install --save-dev nodemon
7
  • Create (method POST):
    npm install mysql --save
    
    1
npm install --save-dev nodemon
8
  • Update (method PUT):
    npm install mysql --save
    
    4
npm install --save-dev nodemon
9

Hướng dẫn can javascript use api? - javascript có thể sử dụng api?

  • Delete (method DELETE):
    npm install mysql --save
    
    4
npm install express --save
0

OK, như vậy mình đã hướng dẫn xong cách xây dựng 1 RESTful API đơn giản với ngôn ngữ NodeJS, bài viết dựa trên kinh nghiệm của bản thân, nếu có gì sai sót mong các bạn comment để mình sửa nhé )

Hướng dẫn can javascript use api? - javascript có thể sử dụng api?
)

Các bạn có thể tham khảo repo github của mình ở đây nhé: https://github.com/tienphat/api_nodejs_example

Nếu các bạn yêu thích bài viết và nội dung mình chia sẻ, bạn có thể tặng mình 1 cốc coffe nha ^^. Tặng liền! Cảm ơn bạn rất nhiều!

Thanks for reading!