Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức send(), sendStatus() và json() trong Node.js (Express)


Các hàm send() và json() dùng để gửi phản hồi trực tiếp từ server đến client. send() gửi dữ liệu dạng chuỗi, json() gửi dạng JSON. sendStatus() gửi mã trạng thái HTTP: 200 (Thành công), 404 (Không tìm thấy), 201 (Đã tạo), 503 (Server không thể truy cập), v.v.

Điều kiện tiên quyết

  • Node.js

  • Express.js

Cài đặt

Cài module express:

npm install express

Ví dụ - sendStatus()

Tạo file sendStatus.js và sao chép mã. Chạy lệnh:

node sendStatus.js

sendStatus.js

// Import express
const express = require('express');
const app = express();

// Phản hồi cho đường dẫn '/'
app.get('/', (req, res) => {
    // Trạng thái: 200 (OK)
    res.sendStatus(200);
})

// Khởi động server cổng 3000
app.listen(3000, () => {
    console.log("Server đang chạy");
});

Kết quả

C:\home\node>> node sendStatus.js

Truy cập trình duyệt: https://localhost:3000

Phương thức send(), sendStatus() và json() trong Node.js (Express)

Ví dụ - send()

Tạo file send.js và sao chép mã. Chạy lệnh:

node send.js

send.js

// Import express
const express = require('express');
const app = express();

// Khởi tạo tiêu đề
var heading = "Welcome to TutorialsPoint !";

// Phản hồi cho đường dẫn '/'
app.get('/', (req, res) => {
    // Gửi văn bản tiêu đề
    res.send(heading);
})

app.listen(3000, () => {
    console.log("Server đang chạy");
});

Kết quả

C:\home\node>> node send.js

Truy cập: https://localhost:3000

Phương thức send(), sendStatus() và json() trong Node.js (Express)

Ví dụ - json()

Tạo file json.js và sao chép mã. Chạy lệnh:

node json.js

json.js

// Import express
const express = require('express');
const app = express();

// Khởi tạo dữ liệu JSON
var data = {
    portal: "TutorialsPoint",
    tagLine: "SIMPLY LEARNING",
    location: "Hyderabad"
}

app.get('/', (req, res) => {
    // Gửi dữ liệu JSON
    res.json(data);
})

app.listen(3000, () => {
    console.log("Server đang chạy");
});

Kết quả

C:\home\node>> node json.js

Truy cập: https://localhost:3000

Phương thức send(), sendStatus() và json() trong Node.js (Express)