Lập trình website – api bằng nodejs – Học lập trình, học sử dụng máy tính từ số 0 – ZeZo.dev https://zezo.dev Fri, 29 Nov 2024 17:26:21 +0000 vi hourly 1 https://wordpress.org/?v=6.7.1 https://zezo.dev/wp-content/uploads/2024/11/cropped-zzel-32x32.png Lập trình website – api bằng nodejs – Học lập trình, học sử dụng máy tính từ số 0 – ZeZo.dev https://zezo.dev 32 32 Code đọc file html trong nodejs https://zezo.dev/view/code-doc-file-html-trong-nodejs Fri, 29 Nov 2024 17:26:21 +0000 https://zezo.dev/?p=271 Bước 1: Tạo 1 thư mục là DocFile, bên trong tạo file index.js với nội dung bên dưới.

Bước 2: Tạo file a.html với nội dung html bất kỳ

Bước 3: Chạy node index.js sau đó vào trình duyệt web nhập vào địa chỉ /a.html để xem kết quả có load được file html lên không

 

const http = require("http")
const fs = require('fs');
const { join } = require("path");
server = http.createServer((req, res) => {
    console.log(req.url);
    if (req.url == '/favicon.ico') {
        console.log("Lấy icon biểu tượng web");
    } else if (req.url == '/') {
        res.writeHead(200, "OK", { 'Content-type': 'text/html' });
        res.write('Home', (err) => { console.log(err); }); res.end();
    } else {
        // đọc file bất kỳ theo tên file được truyền trên url
        // console.log(req.url); 
        // đọc file.VD: url = /a.html ==> req.url.substring(1) --> lấy tên file từ ký tự thứ 1 đến hết 
        fs.readFile(req.url.substring(1), (err, data) => {
            if (err) {
                // throw err res.writeHead(404,{'Content - type':'text / html'}); 
                return res.end();
            }; res.writeHead(200, "OK",
                { 'Content - type': 'text / html' });
            res.write(data.toString('utf8'))
            return res.end();
        })
    }
});
server.listen(80); console.log("server dang chay port 80");

 

]]>
Tạo website đa ngôn ngữ Nodej Express bằng thư viện i18next https://zezo.dev/view/tao-website-da-ngon-ngu-nodej-express-bang-thu-vien-i18next Fri, 29 Nov 2024 16:35:24 +0000 https://zezo.dev/?p=199

Bước 1: Cài thư viện

npm install i18next i18next-http-backend i18next-express-middleware 

Bước 2: Tạo file cấu hình i18n.js

const i18next = require('i18next');
const Backend = require('i18next-http-backend');
const middleware = require('i18next-express-middleware');

i18next
  .use(Backend)
  .use(middleware.LanguageDetector)
  .init({
    fallbackLng: 'en',
    backend: {
      loadPath: __dirname + '/locales/{{lng}}/{{ns}}.json',
      addPath: __dirname + '/locales/{{lng}}/{{ns}}.missing.json',
    },
    detection: {
      order: ['querystring', 'cookie'],
      caches: ['cookie'],
    },
  });

module.exports = i18next;

Bước 3: Tạo thư mục ngôn ngữ

Trong thư mục website, tạo thư mục tên là locales. Trong thư mục này tạo các thư mục con chứa ngôn ngữ.

Ví dụ: en/translation.json

{
  "greeting": "Hello World!"
}

và vi/translation.json 

{
  "greeting": "Xin chào thế giới!"
}

 

Bước 4: Tích hợp vào Express

Trong file app.js nhúng file cấu hình vào

const i18next = require('./i18n');
app.use(i18next.middleware.handle(i18next));

Sử dụng bằng cú pháp:

req.t('greeting')

Bước 5: Chạy ứng dụng

http://localhost:3000/?lng=vi
http://localhost:3000/?lng=en 
hoặc
http://localhost:3000/
]]>
Hướng dẫn sử dụng Retrofit upload file ảnh lên API – Phần MainActivity https://zezo.dev/view/huong-dan-su-dung-retrofit-upload-file-anh-len-api-phan-mainactivity Fri, 29 Nov 2024 15:13:02 +0000 https://zezo.dev/?p=194 Phần này nối tiếp bài viết https://zezo.dev/view/huong-dan-su-dung-retrofit-upload-file-anh-len-api/


import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.picasso.Picasso;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    

    private static final int PICK_IMAGE_REQUEST_CODE = 100;
    
    private Uri imageUri;
    private static final String BASE_URL = "http://10.0.2.2:3000/api/"; // Replace with your base URL
    static  final String TAG = "zzzzzzzz";

    ImageView img_preview;
    TextView tv01;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv01 = findViewById(R.id.tv01);
        img_preview = findViewById(R.id.img_preview);
        findViewById(R.id.btn_browsefile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pickImage();
            }
        });

        findViewById(R.id.btn_upload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uploadFile();
            }
        });
        if (Build.VERSION.SDK_INT >= 30){
            if (!Environment.isExternalStorageManager()){
                Intent getpermission = new Intent();
                getpermission.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivity(getpermission);
            }
        }

    }

    private void pickImage() {
//        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
         Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);
        startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
            imageUri = data.getData();
            Log.d(TAG, "onActivityResult: " + imageUri);
            tv01.setText(imageUri.toString());
        }
    }

    private void uploadFile() {
        if (imageUri == null) {
            Log.d(TAG, "uploadFile: URI null");
            tv01.setText("URI file null");
            return;
        }

        File file = new File(getRealPathFromURI(imageUri));

        Log.d(TAG, "uploadFile: " + file.toString());


        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file); 
        // *** chú ý cái này MediaType.parse("image/*")  phải để là  image/* thì trên server mới nhận diện ra file ảnh.
        
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("hinh_anh", file.getName(), requestBody);

        Log.d(TAG, "uploadFile: "+ filePart.body().toString());
        Gson gson = new GsonBuilder().setLenient().create();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        ApiService apiService = retrofit.create(ApiService.class);

        Call<KetQuaUpload> objCall = apiService.uploadFile(filePart);
        objCall.enqueue(new Callback<KetQuaUpload>() {
            @Override
            public void onResponse(Call<KetQuaUpload> call, Response<KetQuaUpload> response) {
                Log.d(TAG, "onResponse: " + response.body());
                if (response.isSuccessful()) {
                    // Upload thành công
                    Log.d(TAG, "onResponse: " + response.body().toString());
                    KetQuaUpload objKQ = response.body();
                    if(objKQ.error == null){
                        // không có lỗi, hien thi anh
                        Picasso.get().load(objKQ.link_anh).into(img_preview);
                    }
                } else {
                    // Upload thất bại
                }
            }

            @Override
            public void onFailure(Call<KetQuaUpload> call, Throwable throwable) {
                    throwable.printStackTrace();
            }
        });



    }

    private String getRealPathFromURI(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        Log.d(TAG, "getRealPathFromURI: "  + cursor.getCount());
        if (cursor != null) {
            cursor.moveToFirst();
            for(int i = 0; i< cursor.getColumnCount(); i++){
                Log.d(TAG, "getRealPathFromURI: " + cursor.getColumnName(i) + "==>" + cursor.getString(i));

            }

            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            String path = cursor.getString(columnIndex);
            cursor.close();
            return path;
        } else {
            return null;
        }
    }
}

 

 

 

]]>
Hướng dẫn sử dụng Retrofit upload file ảnh lên API https://zezo.dev/view/huong-dan-su-dung-retrofit-upload-file-anh-len-api Fri, 29 Nov 2024 15:10:51 +0000 https://zezo.dev/?p=192 Trước hết bạn cần xây dựng API, hãy xem bài viết https://zezo.dev/view/huong-dan-tao-route-upload-file-voi-multer-trong-nodejs/

Sau khi có API rồi thì bạn tiến hành xây dựng code Android Java để thực hiện upload ảnh.

 

Bước 1: Tạo project mới và nhúng thư viện

Bạn tự tạo 1 project mới và nhúng các thư viện sau vào file build.gradle ở cấp độ module

 

    implementation ("com.squareup.retrofit2:retrofit:2.11.0")
    implementation ("com.squareup.retrofit2:converter-gson:2.11.0")
    implementation ("com.squareup.okhttp3:okhttp:4.12.0")
    implementation ("androidx.media:media:1.4.0")
    implementation ("com.squareup.picasso:picasso:2.8")

Sau khi nhúng thư viện nhớ bấm Sync để cập nhật thư viện

 

Bước 2: Tạo file interface ApiService  để retrofit làm việc

import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public interface ApiService {

    @Multipart
    @POST("demo-upload")
    Call<KetQuaUpload> uploadFile(@Part  MultipartBody.Part file);
}

Bước 3: Tạo layout cho activity

Trên Layout có các nút bấm

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/tv01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Demo Upload file"
       />

    <ImageView
        android:id="@+id/img_preview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/btn_browsefile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Browse File"/>
    <Button
        android:id="@+id/btn_upload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload File"/>
</LinearLayout>

Bước 4: Khai báo Manifest

 

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
    
    <uses-permission android:name="android.permission.INTERNET"/>

Đặc biệt chú ý trong thẻ application của Mainifest phải có 2 thuộc tính sau

<application
        android:requestLegacyExternalStorage="true"
        android:usesCleartextTraffic="true"

Bước 5: Tạo một lớp là KetQuaUpload để convert kết quả trả về từ server sang đối tượng java cho dễ dùng

public class KetQuaUpload {
    public String link_anh;
    public String error;

    public String toString(){
        return  "Error: "+ error + "\nLink: " + link_anh;
    }
}

Tiếp theo viết code cho MainActivity bạn xem ở bài viết tiếp theo https://zezo.dev/view/huong-dan-su-dung-retrofit-upload-file-anh-len-api-phan-mainactivity

 

]]>
Hướng dẫn tạo route upload file với multer trong nodejs https://zezo.dev/view/huong-dan-tao-route-upload-file-voi-multer-trong-nodejs Fri, 29 Nov 2024 15:09:13 +0000 https://zezo.dev/?p=188 Bước 1: Tạo ứng dụng expressjs bằng công cụ generator

https://expressjs.com/en/starter/generator.html

hoặc bạn có thể sử dụng code mãu API sau Code-API-ExpressJS

Chú ý: Trong code chưa có thư mục node_modules nên sau khi tải về giải nén bạn cần chạy lệnh dưới để cài thư viện

npm i

Bài viết này sẽ hướng dẫn bạn tạo thêm route trong API để thực hiện upload file

Bước 2: Cài thư viện multer

https://www.npmjs.com/package/multer

npm install --save multer

Bước 3: Chỉnh sửa route api

Nếu bạn tạo project mới thì phải tạo file api.js mới, nếu dùng code mẫu ở trên thì bạn mở file api.js có sẵn trong thư mục routes để chỉnh sửa

– Bên dưới dòng nhúng thư viện bạn thêm lệnh nhúng thư viện Multer

const multer  = require('multer')
var objUpload = multer( { dest: './tmp'}); // vào thư mục code tạo 1 thư mục tên là tmp

– Xuống cuối file trước dòng module.exports = router; bạn viết thêm lệnh tạo route

router.post('/demo-upload',objUpload.single('hinh_anh'), demo_upload);

Bước 4: Vào file controller để viết hàm xử lý upload

Trong code mẫu này tên file controller là xeMayController.js, bạn mở file này ra và thêm vào đầu file lệnh nhúng thư viên fs để gọi hàm làm việc với file

var fs = require('fs'); // thư viện xử lý về file

Tiếp theo bạn viết thêm hàm xử lý việc upload file:

– Trong thư mục public/ của code web, bạn tạo một thư mục con là uploads

– Tiếp theo bạn viết code cho hàm upload như sau (Chú ý đọc kỹ lời giải thích trong hàm)

 

exports.demo_upload = (req, res, next) => {
    try {
        if (fs.existsSync(req.file.path)) {
            // có tồn tại file
            // định nghĩa đường dẫn file mới để lưu trữ
            let file_path = './public/uploads/' + req.file.originalname;
            // có thể kiểm tra định dạng file ....
            console.log(req.file);
            // { kết quả log có các thuộc tính, bạn muốn kiểm tra gì thì req.file.xxxxx
            //     fieldname: 'anh',
            //     originalname: 'giao-dien-mua-hang.png',
            //     encoding: '7bit',
            //     mimetype: 'image/png',
            //     destination: './tmp',
            //     filename: '280990afd14931ba2d750ff76630544e',
            //     path: 'tmp/280990afd14931ba2d750ff76630544e',
            //     size: 676236
            //   }
            // ở đây tạm thời chỉ cho upload ảnh: 
            if (req.file.mimetype.indexOf('image') == -1) {
                // định dạng file chuẩn ảnh
                msg = 'Không đúng định dạng ảnh';
                return res.status(400).json({ error: 'Lỗi không đúng định dạng ảnh' });// thoát khỏi hàm
            }
            // đến đây là phù hợp điều kiện, chuyển file từ thư mục tmp và thư mục uploads để lưu trữ lâu dài
            fs.renameSync(req.file.path, file_path);
            // không có lỗi thì sẽ chạy xuống lệnh dưới đây, bạn ghép nối chuỗi thành link ảnh
            // chú ý: http://localhost:3000 là đoạn domain bạn cần thay đổi cho phù hợp với web của bạn
            let link_anh = 'http://localhost:3000/uploads/' + req.file.originalname;
            res.status(200).json({ error: null, link_anh: link_anh });
        } else {
            res.status(404).json({ error: 'Không có file upload' });
        }
    } catch (ex) {
        res.status(400).json({ error: ex.message });
    }
}

Kết quả chạy trên postman để upload ảnh: Bạn thấy kết quả trả về có link ảnh vậy là thành công upload ảnh độc lập. Bạn có link ảnh rồi thì có thể ghép vào bài viết hoặc sản phẩm để sau hiển thị lên màn hình, như vậy bạn sẽ mang code upload này ghép vào code.

 

 

]]>
Hướng dẫn phân trang trong danh sách dữ liệu API viết bằng nodejs https://zezo.dev/view/huong-dan-phan-trang-trong-danh-sach-du-lieu-api-viet-bang-nodejs Fri, 29 Nov 2024 08:34:10 +0000 https://zezo.dev/?p=170 Bài viết hướng dẫn cơ bản nhất về viết một ứng dụng nodejs có kết nối mongodb lấy danh sách bài viết sau đó phân trang.

Bước 1: Cài mongodb trên máy cá nhân nếu chưa có

Bạn có thể dùng bản mongo online nhưng sẽ có giới hạn về lưu trữ và có ảnh hưởng bởi tốc độ đường truyền internet và cấu hình IP.

– Link tải mongodb server https://www.mongodb.com/try/download/community

– Link tải công cụ compass để có giao diện quản lý mongodb https://www.mongodb.com/en-us/products/tools/compass

Sau khi bạn cài đặt xong (cài đủ 2 thứ trên) bạn mở compass đã cài đặt, mặc định sẽ hiển thị một kết nối mẫu, bạn bấm vào Connect để bắt đầu kết nối sẽ vào được giao diện quản lý Mongo.

mongodb

Cách sử dụng phần mềm và các thao tác trên đó sẽ giới thiệu ở bài viết khác, bạn có thể tra cứu thêm trên internet.

Bước 2: Tạo ứng dụng Nodejs với express-generator

Bạn mở phần mền VS Code hoặc cửa sổ lệnh, đứng tại thư mục sẽ chứa code ứng dụng bạn chạy các lệnh sau:

– Chạy lệnh cài express-generator để tạo code

npm install -g express-generator

– Chạy tiếp lệnh tạo project với tên project là Api_Zezo_Dev

express --view=ejs Api_Zezo_Dev

– Tiếp theo CD vào thư mục code vừa tạo

cd Api_Zezo_Dev

– Tiếp theo cài thư viện node_modules

npm i

– Tiếp theo cài thêm nodemon để giám sát chỉnh sửa file, mỗi khi sửa file sẽ tự khởi động lại server

npm install -g nodemon

– Tiếp theo chạy lệnh:

nodemon npm start

Ở bước này có thể xảy ra lỗi có liên quan chữ “Policy”, bạn cần đọc kỹ thông báo lỗi. Lỗi này do VS Code không được cấp quyền thực thi JS ở bên ngoài. Bạn xem cách sửa ở bài viết này https://zezo.dev/view/hoc-nodejs-nhu-the-nao

– Tiếp theo chạy xong bạn mở trình duyệt web nhập vào địa chỉ:  http://localhost:3000, nếu nhìn thấy nội dung có tiêu đề Express là thành công.

 

Bước 2: Cài thư viện mongoose để kết nối CSDL mongo từ nodejs

https://mongoosejs.com/docs/

Công việc cài đặt rất đơn giản

npm install mongoose --save

Bước 3: Tạo cấu trúc MVC

Bạn nên tạo thói quen tạo cấu trúc MVC cho ứng dụng để phát triển code

Api_Zezo_Dev/
            controllers
            models
            views   <-- thư mục này mặc định đã có, nhưng không cần dùng đến vì viết API sẽ không cần view.
            ....    <-- các thư mục khác theo mặc định như public, routes, middlewares....

Bước 4: Tạo model

– Trong thư mục model, bạn tạo file kết nối CSDL là db.js

const mongoose = require('mongoose');
mongoose.connect( 'mongodb://127.0.0.1:27017/demo_api_zezo_dev')
       .catch( (err) =>{
               console.log("Loi ket noi CSDL");
               console.log(err);
       });
      
module.exports = {mongoose}

– Tiếp theo bạn tạo file todoModel.js. Bài viết này demo với 2 trường dữ liệu title và status

 

const {mongoose} = require('./db');
const todoSchema = new mongoose.Schema(
    {
        title:{type:String, required: true},
        status:{type:Number, required: true, default: 0}
    },
    {
        collection: 'todos'  // đặt tên cho collection
    }
);
let todoModel = mongoose.model('todoModel', todoSchema);
module.exports = {todoModel}

 

Bước 5: Tạo cấu trúc hàm trong controller

Trong thư mục controllers, bạn tạo một file là todoController.js

 

const { todoModel } = require('../models/todoModel');
  
exports.getList = async (req, res, next) => {
	// lát nữa viết code chi tiết cho hàm sau
});

Bước 6: Tạo route

– Trong thư mục routes, bạn tạo file api.js

var express = require('express');
var router = express.Router();
var todoCtrl = require('../controllers/todoController');
// lấy danh sách todo, link GET http://localhost:3000/api/todos 
router.get('/todos', todoCtrl.getList );
module.exports = router;

– Tiếp theo bạn vào file app.js khai báo nhúng file api và khai báo route

var apiRouter = require('./routes/api');
app.use('/api', apiRouter);

Bước 7: Viết chi tiết cho hàm trong controller

exports.getList = async (req, res, next) => {
    let limit = 3; // số bản ghi trên 1 trang, cái này server tự quy định
    // khai báo một đối tượng dùng để cài dữ liệu trả về client theo một format nhất định
    let dataRes = {
        msg:'',
        status:0,
        data:[],
        totalPages:0,
        currentPage: 1, // mặc định là trang 1
        totalItems: 0
    };
    try {
    	// nếu có truyền vào địa chỉ một tham số là page thì gán nó vào currentPage
        if(typeof(req.query.page) != 'undefined' && !isNaN(req.query.page)){
            dataRes.currentPage = req.query.page;
        }
        // đếm tổng số bản ghi hợp lệ trong collection
        let totalItems = await todoModel.countDocuments();
        // tính ra tổng số trang, mỗi trang có số lượng bản ghi là giá trị của biến limit
        let totalPages = Math.ceil(totalItems / limit);
        // tính số bản ghi sẽ bỏ qua, ví dụ: mỗi trang 3 bản ghi, thì khi người dùng vào trang 2, sẽ phải bỏ qua 3 bản ghi đầu, lấy dữ liệu từ bản ghi thứ 4 đến hết số lượng giới hạn bản ghi limit.
        const skip = (dataRes.currentPage - 1) * limit; // Số lượng bản ghi cần bỏ qua
        // thực thi lệnh lấy dữ liệu
        let list = await todoModel.find()
                        .skip(skip)
                        .limit(limit);
        // gắn dữ liệu vào đối tượng res cho đúng format
        dataRes.status = 1;
        dataRes.msg ='Lấy danh sách thành công';
        dataRes.data = list;
        dataRes.totalPages =  totalPages;
        dataRes.totalItems = totalItems;
 
        res.status(200).json(dataRes);
    } catch (error) {
        dataRes.msg = error.message; 
        res.status(400).json(dataRes);
    }
}

Bước 8: Thử nghiệm ứng dụng

Bạn đã chạy lệnh nodemon ở trên thì không cần chạy lại npm start nữa.

 

Bạn có thể truy cập link api bằng trình duyệt web hoặc postman. Kết quả chạy lần đàu bạn sẽ thấy:

http://:3000/api/todos?page=1

{
    "msg": "Lấy danh sách thành công",
    "status": 1,
    "data": [],
    "totalPages": 0,
    "currentPage": 1,
    "totalItems": 0
}

Giờ chưa có chức năng thêm, bạn hãy vào phần mềm Compass để nhập thủ công vào collection todos khoảng 10 bản ghi.

ket qua mongodb

Tiếp theo bạn quay lại postman hoặc trình duyệt web bạn truy cập lại link api để xem kết quả trả về danh sách, bạn sẽ thấy phần data có 3 bản ghi, totalItems có 10 bản ghi ==> trong code đã giới hạn limit là 3 bản ghi trên 1 trang. Khi sử dụng bạn cần truyền thêm tham số page=x để biết sẽ truy cập vào trang thứ bao nhiêu. Bạn hãy thử thay đổi page=2 hoặc 3 hoặc 4 để xem kết quả.

ket qua mongodb

Với page=4 link truy cập GET: http://:3000/api/todos?page=4   sẽ có kết quả:

{
    "msg": "Lấy danh sách thành công",
    "status": 1,
    "data": [
        {
            "_id": "6616ae38d3fb462b1a9528e9",
            "title": "Việc số 10",
            "status": 1
        }
    ],
    "totalPages": 4,
    "currentPage": "4",
    "totalItems": 10
}

 

]]>
Làm quen với Router và Controller trong expressjs https://zezo.dev/view/lam-quen-voi-router-va-controller-trong-expressjs Fri, 29 Nov 2024 08:23:04 +0000 https://zezo.dev/?p=160 1.Tạo controller
  • Tạo thư mục controllers trong thư mục ứng dụng
  • Tạo file sanpham.controller.js

exports.getListSanPham = (req,res,next)=>{    res.render( ‘sanpham/list’, { tieuDe: “Danh sách SP đã bán” } ) }

 

2. Tạo view

  • Tạo thư mục là sanpham ở trong thư mục /views
  • Trong thư mục sanpham vừa tạo, hãy tạo thêm file list.ejs
<h1>Danh sách sản phẩm</h1>
Biến truyền từ Controller: <%= tieuDe  %>

3. Tạo router

  • Tạo thêm file sanpham.js trong thư mục routers/
var express = require('express');
var router = express.Router();
// nhúng controller 
var sanphamController = require('../controllers/sanpham.controller');
router.get('/list', sanphamController.getListSanPham  );
module.exports = router;
// http://localhost:3000/sp/list

4. Khai báo router trong file app.js

Viết lệnh sau ở phía trước dòng var app = express();

var sanphmRouter = require('./routes/sanpham');

 

Viết lệnh sau ở phía dưới lệnh app.use(‘/’, indexRouter);

app.use('/sp', sanphmRouter);

 

5. Chạy ung dung

http://localhost:3000/sp/list

]]>
Code nodejs sử dụng module fs đọc file html trả về client 2 https://zezo.dev/view/code-nodejs-su-dung-module-fs-doc-file-html-tra-ve-client-2 https://zezo.dev/view/code-nodejs-su-dung-module-fs-doc-file-html-tra-ve-client-2#respond Thu, 28 Nov 2024 09:54:19 +0000 https://zezo.dev/?p=48 Tiêp theo bài viết https://zezo.dev/view/code-nodejs-su-dung-module-fs-doc-file-html-tra-ve-client/

// đọc file html trả về trình duyệt 
const http = require("http");
// sử dụng module fs để đọc file const fs = require("fs"); 
console.log("Bắt đầu tạo server...");
const server = http.createServer(function (req, res) {
    console.log("Truy cập: " + req.url);
    // nếu vào trang c.html thì tự chuyển về trang a.html 
    // còn lại thì tự load file và show lên 
    if (req.url == '/c.html') {
        // tự động chuyển sang địa chỉ mới 
        console.log("Chuyển sang địa chỉ mới vì không tồn tại c.html");
        res.writeHead(301, { 'Location': 'http://' + req.headers['host'] });
        return res.end();
        // kết thúc
    } else if (req.url == '/') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        return res.end("<h1>Trang home</h1>"); // trang chủ
    } else {
        // đọc file và trả về nội dung
        fs.readFile(req.url.substring(1),
            function (err, data) {
                if (err) console.log(err);
                else res.write(data.toString('utf8'));
                return res.end();
            }); return res.end();
    }
});
server.listen(80, "localhost", function () {
    console.log("Server đang chạy cổng 80: http://localhost");
});
]]>
https://zezo.dev/view/code-nodejs-su-dung-module-fs-doc-file-html-tra-ve-client-2/feed 0
Code nodejs sử dụng module fs đọc file html trả về client https://zezo.dev/view/code-nodejs-su-dung-module-fs-doc-file-html-tra-ve-client https://zezo.dev/view/code-nodejs-su-dung-module-fs-doc-file-html-tra-ve-client#respond Thu, 28 Nov 2024 09:52:20 +0000 https://zezo.dev/?p=45 Bước 1: Tạo thư mục để chứa file, tạo file a.html trong thư mục, tạo thêm file server.js để viết code bên dưới

Bước 2: viết code bên dưới vào file server để chạy


// đọc file html trả về trình duyệt 
const http = require("http");

// sử dụng module fs để đọc file 
const fs = require("fs");

console.log("Bắt đầu tạo server...");

const server = http.createServer(function (req, res) {
    console.log("Truy cập: " + req.url);

    if (req.url == '/a.html') {

        // http://localhost/a.html 

        // đọc file trả về trình duyệt

        fs.readFile("./a.html", function (err, data) {

            if (err) throw err; // có lỗi thì in ra và dừng các lệnh phía sau 

            // không có lỗi thì in xuống trình duyệt res.writeHead(200, {'Content-Type':'text/html'}); 

            res.write(data.toString('utf8'));

            // không gạch ngang ở utf8 
            return res.end();
        });
    } else {

        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write("Trang chu");

        // muốn viết tiếng Việt có dấu thì trong nội dùng write thêm thẻ: 
        return res.end();
    }
});

server.listen(80, "localhost", function () {

    console.log("Server đang chạy cổng 80: http://localhost");
});

 

 

]]>
https://zezo.dev/view/code-nodejs-su-dung-module-fs-doc-file-html-tra-ve-client/feed 0
Học Nodejs như thế nào? https://zezo.dev/view/hoc-nodejs-nhu-the-nao https://zezo.dev/view/hoc-nodejs-nhu-the-nao#respond Thu, 28 Nov 2024 09:10:21 +0000 https://zezo.dev/?p=35 Kiến thức cơ bản cần thiết

Nodejs là framework mã nguồn mở được xây dựng bằng ngôn ngữ lập trình JavaScript, không phụ thuộc hệ điều hành và có thể tạo server, ứng dụng web…

“Node.js® is a free, open-source, cross-platform JavaScript runtime environment that lets developers create servers, web apps, command line tools and scripts.”

Để học được nodejs, bạn cần có kiến thức cơ bản về lập trình JavaScript, có thêm html, css thì càng tốt.

Công cụ và tiện ích

👉 Phần mềm soạn thảo code: 

Visual studio code https://code.visualstudio.com/download

hoặc phpstorm https://www.jetbrains.com/phpstorm/

hoặc sublimetext https://www.sublimetext.com/download

hoặc bất kỳ phần mềm soạn thảo code nào khác

👉 Cài đặt nodejs tại

Tải bản mới nhất tại https://nodejs.org/en

Nếu chạy lệnh trên cửa sổ lệnh của Visual Studio Code mà báo lỗi liên quan tới chữ “Policy”  thì mở cửa sổ Powershell với quyền Administrator sau đó chạy lệnh dưới và bấm phím a để mở quyền thực thi script.

Set-ExecutionPolicy –ExecutionPolicy RemoteSigned

Bắt đầu như thế nào

Sau khi cài đặt xong, tạo một thư mục thực hành nodejs ( ví dụ tạo thư mục ở ổ C:   c:\thuc-hanh-nodejs ), trong thư mục này tạo một file vidu1.js

Viết code cho file này đơn giản

console.log("vi du nodejs");

Sau khi lưu file, mở cửa sổ lệnh để thực hiện chạy.

 

Bước 1: chạy lệnh DIR (và bấm enter)

dir

nếu nhìn thấy tên file vidu1.js thì ok, nếu chưa nhìn thấy thì phải dùng lệnh CD ở dưới để vào thư mục chứa code

cd c:\thuc-hanh-nodejs

sau đó viết lại lệnh dir để xem đã nhìn thấy thư mục chưa

dir

Bước 2: Sau khi nhìn thấy file vidu1.js thì nhập lệnh sau để bắt đầu chạy code

node vidu1.js

kết quả hiển thị trên cửa sổ lệnh chữ bên dưới là thành công.

vi du nodejs

Tiếp theo nên học gì

– Học các cú pháp tạo server của nodejs, tìm hiểu về req, res
– Thực hành tạo file html và send xuống client
– Học về expressjs https://expressjs.com/en/starter/generator.html
– Học về ejs template
– Học mongodb https://zezo.dev/view/mongodb-cheat-sheet-tom-luoc-cau-lenh-tuong-tac-trong-mongodb/
– Học cách tương tác mongodb
– Học cách upload file
– Học cách tạo middleware
– Học cách tạo jwt https://jwt.io/
– Học thêm về nginx để tự triển khai server
– Học pm2 để quản trị web nodejs
…. học nhiều thứ khác nữa tùy công việc của bạn thời điểm đó.

 

]]>
https://zezo.dev/view/hoc-nodejs-nhu-the-nao/feed 0