Axios nodejs

trong v1. 2. 1 sửa lỗi này

Bạn cần thêm

$ node product.js
{
    "meta": {
        "count": 32,
        "limit": 10,
        "page": 1,
        "next_url": "/shop/products/?page=2&limit=10"
    },
    "products": [
        {
            "name": "Bananas",
            "product_url": "/shop/products/3"
        },
        {
            "name": "Oranges",
            "product_url": "/shop/products/10"
        },
        {
            "name": "Pineapples",
            "product_url": "/shop/products/33"
        },
        {
            "name": "Dried Pineapples",
            "product_url": "/shop/products/42"
        },
        {
            "name": "Cranberries",
            "product_url": "/shop/products/57"
        },
        {
            "name": "Mango fresh",
            "product_url": "/shop/products/62"
        },
        {
            "name": "Raspberries",
            "product_url": "/shop/products/90"
        },
        {
            "name": "Cherries",
            "product_url": "/shop/products/7"
        },
        {
            "name": "Apple",
            "product_url": "/shop/products/18"
        },
        {
            "name": "Green Grapes",
            "product_url": "/shop/products/11"
        }
    ]
}
6 với
$ node product.js
{
    "meta": {
        "count": 32,
        "limit": 10,
        "page": 1,
        "next_url": "/shop/products/?page=2&limit=10"
    },
    "products": [
        {
            "name": "Bananas",
            "product_url": "/shop/products/3"
        },
        {
            "name": "Oranges",
            "product_url": "/shop/products/10"
        },
        {
            "name": "Pineapples",
            "product_url": "/shop/products/33"
        },
        {
            "name": "Dried Pineapples",
            "product_url": "/shop/products/42"
        },
        {
            "name": "Cranberries",
            "product_url": "/shop/products/57"
        },
        {
            "name": "Mango fresh",
            "product_url": "/shop/products/62"
        },
        {
            "name": "Raspberries",
            "product_url": "/shop/products/90"
        },
        {
            "name": "Cherries",
            "product_url": "/shop/products/7"
        },
        {
            "name": "Apple",
            "product_url": "/shop/products/18"
        },
        {
            "name": "Green Grapes",
            "product_url": "/shop/products/11"
        }
    ]
}
7 trong axios. lấy tiêu đề

Mặc định của nó là

$ node product.js
{
    "meta": {
        "count": 32,
        "limit": 10,
        "page": 1,
        "next_url": "/shop/products/?page=2&limit=10"
    },
    "products": [
        {
            "name": "Bananas",
            "product_url": "/shop/products/3"
        },
        {
            "name": "Oranges",
            "product_url": "/shop/products/10"
        },
        {
            "name": "Pineapples",
            "product_url": "/shop/products/33"
        },
        {
            "name": "Dried Pineapples",
            "product_url": "/shop/products/42"
        },
        {
            "name": "Cranberries",
            "product_url": "/shop/products/57"
        },
        {
            "name": "Mango fresh",
            "product_url": "/shop/products/62"
        },
        {
            "name": "Raspberries",
            "product_url": "/shop/products/90"
        },
        {
            "name": "Cherries",
            "product_url": "/shop/products/7"
        },
        {
            "name": "Apple",
            "product_url": "/shop/products/18"
        },
        {
            "name": "Green Grapes",
            "product_url": "/shop/products/11"
        }
    ]
}
8 trong V1. 2. 0 axios đã sửa lỗi này trong v1. 2. 1

mã demo trong v1. 2. 0

const axios = require('axios')

const getProducts = async () => {
    try {
        const resp = await axios.get(
            'https://api.predic8.de/shop/products/',
            {
                headers: {
                    'Accept-Encoding': 'application/json',
                }
            }
        );
        console.log(JSON.stringify(resp.data, null, 4));
    } catch (err) {
        // Handle Error Here
        console.error(err);
    }
};

getProducts();

HOẶC đã sửa trong v1. 2. 1

const axios = require('axios')

const getProducts = async () => {
    try {
        const resp = await axios.get(
            'https://api.predic8.de/shop/products/'
        );
        console.log(JSON.stringify(resp.data, null, 4));
    } catch (err) {
        // Handle Error Here
        console.error(err);
    }
};

getProducts();

Kết quả

$ node product.js
{
    "meta": {
        "count": 32,
        "limit": 10,
        "page": 1,
        "next_url": "/shop/products/?page=2&limit=10"
    },
    "products": [
        {
            "name": "Bananas",
            "product_url": "/shop/products/3"
        },
        {
            "name": "Oranges",
            "product_url": "/shop/products/10"
        },
        {
            "name": "Pineapples",
            "product_url": "/shop/products/33"
        },
        {
            "name": "Dried Pineapples",
            "product_url": "/shop/products/42"
        },
        {
            "name": "Cranberries",
            "product_url": "/shop/products/57"
        },
        {
            "name": "Mango fresh",
            "product_url": "/shop/products/62"
        },
        {
            "name": "Raspberries",
            "product_url": "/shop/products/90"
        },
        {
            "name": "Cherries",
            "product_url": "/shop/products/7"
        },
        {
            "name": "Apple",
            "product_url": "/shop/products/18"
        },
        {
            "name": "Green Grapes",
            "product_url": "/shop/products/11"
        }
    ]
}

Kiểm tra các bài viết đó nếu bạn muốn tìm hiểu cách trích xuất lệnh curl từ các yêu cầu do trình duyệt của bạn thực hiện

  • Trình duyệt Chrome
  • Cuộc đi săn
  • firefox

Học NodeJS với tính năng quét web Axios

JavaScript đã trở thành một trong những ngôn ngữ được yêu thích và thường xuyên sử dụng nhất nhờ những phát triển quan trọng mà nó đã trải qua và sự ra đời của thời gian chạy NodeJS. Cho dù đó là ứng dụng web hay ứng dụng di động, JavaScript hiện có sẵn các khả năng cần thiết

Lập trình gửi yêu cầu trong Node. js có thể là một trải nghiệm khó chịu. Đầu tiên, bạn phải chọn một trong nhiều thư viện yêu cầu trong hệ sinh thái. Thứ hai, chúng đều có API hơi khác nhau, điều này gây nhầm lẫn khi bạn chuyển đổi

Bạn cũng phải đảm bảo yêu cầu được định dạng theo cách cụ thể để bên thứ 3 ở đầu nhận chấp nhận yêu cầu đó

Ngay khi bạn bắt đầu làm quen với axios, bạn sẽ sớm phát hiện ra có những khác biệt (tinh tế) về cách sử dụng tùy thuộc vào việc bạn đang ở trong trình duyệt hay Node. js

thật là đau

Chỉ khi tải lên các tệp có axios trong Node. js sẽ dễ dàng như đi dạo trong công viên

Vâng, nó có thể được

Trong bài viết này, bạn sẽ tìm hiểu cách gửi tệp và dữ liệu liên quan bằng cách xây dựng một biểu mẫu. Chúng tôi sẽ đề cập đến hai loại tệp - Bộ đệm và Luồng và cách làm việc với chúng

Trước khi tải tệp lên bằng axios, trước tiên bạn cần tạo một biểu mẫu và nối tệp vào đó. Axios có thể được sử dụng ở cả giao diện người dùng và phụ trợ và thư viện không phân biệt giữa hai. Do đó, việc gửi một tệp có axios trong Node. js tương tự như gửi tệp có axios trong trình duyệt

Bởi vì chúng tôi không có quyền truy cập vào giao diện

$ node product.js
{
    "meta": {
        "count": 32,
        "limit": 10,
        "page": 1,
        "next_url": "/shop/products/?page=2&limit=10"
    },
    "products": [
        {
            "name": "Bananas",
            "product_url": "/shop/products/3"
        },
        {
            "name": "Oranges",
            "product_url": "/shop/products/10"
        },
        {
            "name": "Pineapples",
            "product_url": "/shop/products/33"
        },
        {
            "name": "Dried Pineapples",
            "product_url": "/shop/products/42"
        },
        {
            "name": "Cranberries",
            "product_url": "/shop/products/57"
        },
        {
            "name": "Mango fresh",
            "product_url": "/shop/products/62"
        },
        {
            "name": "Raspberries",
            "product_url": "/shop/products/90"
        },
        {
            "name": "Cherries",
            "product_url": "/shop/products/7"
        },
        {
            "name": "Apple",
            "product_url": "/shop/products/18"
        },
        {
            "name": "Green Grapes",
            "product_url": "/shop/products/11"
        }
    ]
}
9 trong Node. js như chúng tôi làm trong trình duyệt, chúng tôi sử dụng thư viện dữ liệu biểu mẫu để tạo biểu mẫu. Điều này tương tự với phần tử
const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');
0 với loại mã hóa được đặt thành
const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');
1 trong trình duyệt

Để xây dựng một biểu mẫu, hãy tạo một phiên bản FormData mới và sử dụng phương thức

const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');
0 để thêm tệp và các trường bổ sung

// `form-data` library gives us a similar API in Node.js to the `FormData` interface in the browser
const FormData = require('form-data');

// Create a new form instance
const form = new FormData();

// Append text fields to the form
form.append('productName', 'Node.js Stickers');
form.append('productDescription', 'Cool collection of Node.js stickers for your laptop.');

// `file` can either be a Buffer or a Stream
// ⚠️ don't forget the 3rd argument, the file name, when appending a file
form.append('productImage', file, 'stickers.jpg');

Lưu ý rằng khi thêm một tệp vào biểu mẫu, hàm chắp thêm sẽ nhận ba đối số thay vì hai. Đối số thứ ba là tên tệp và nếu nó bị thiếu, tệp sẽ không được gửi đúng cách, vì vậy hãy đảm bảo chuyển nó đi cùng

Đối số thứ hai là chính tệp, có thể là Bộ đệm hoặc Luồng. Hãy xem xét một vài ví dụ thực tế về cách thức và lý do bạn sử dụng cả hai

Bộ đệm tệp (hoặc đốm màu) là thứ bạn sẽ gặp thường xuyên nhất khi xử lý tệp. Về cơ bản, đó là toàn bộ tệp được lưu trữ ở định dạng nhị phân trong bộ nhớ của ứng dụng

Nếu bạn đã quen với multer, thì nó sử dụng

const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');
1 theo mặc định, về cơ bản là lưu trữ các tệp trong bộ nhớ dưới dạng Bộ đệm. Đọc tệp từ đĩa bằng
const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');
2 cũng cung cấp cho bạn tệp được lưu trữ dưới dạng Bộ đệm

Trong cả hai trường hợp, bạn có thể nối thêm bộ đệm tệp vào biểu mẫu FormData

const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');

Bạn cũng có thể nối tệp dưới dạng luồng vào biểu mẫu. Điều này hữu ích khi, ví dụ, khi tệp được tìm nạp từ một tài nguyên bên ngoài. Sau đó, bạn có thể ủy quyền tệp trực tiếp tới một API khác mà không cần lưu trữ cục bộ

________số 8

Một ví dụ điển hình khác là khi bạn xử lý các tệp lớn. Sử dụng luồng thay vì bộ đệm có thể ngăn ứng dụng của bạn tiêu tốn quá nhiều bộ nhớ và cuối cùng bị sập

// Open file as a readable stream
const fileStream = fs.createReadStream('./large-file.zip');

const form = new FormData();
// Pass file stream directly to form
form.append('largeFile', fileStream, 'large-file.zip');

Để tải lên nhiều tệp, bạn chỉ cần

const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');
3 từng tệp một vào biểu mẫu

Bây giờ, hãy gửi biểu mẫu FormData bằng axios. API axios để gửi yêu cầu POST là

const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');
4, ở đâu

  • const form = new FormData();
    
    // File parsed by multer from incoming request
    const file = req.file;
    form.append('file', file.buffer, file.originalname);
    
    // or read from disk
    const file = await fs.readFile('./my-image.jpg');
    form.append('file', file, 'my-image.jpg');
    5 - URL máy chủ sẽ được sử dụng cho yêu cầu
  • const form = new FormData();
    
    // File parsed by multer from incoming request
    const file = req.file;
    form.append('file', file.buffer, file.originalname);
    
    // or read from disk
    const file = await fs.readFile('./my-image.jpg');
    form.append('file', file, 'my-image.jpg');
    6 (tùy chọn) - dữ liệu được gửi dưới dạng nội dung yêu cầu
  • const form = new FormData();
    
    // File parsed by multer from incoming request
    const file = req.file;
    form.append('file', file.buffer, file.originalname);
    
    // or read from disk
    const file = await fs.readFile('./my-image.jpg');
    form.append('file', file, 'my-image.jpg');
    7 (tùy chọn) - đối tượng cấu hình nơi bạn có thể đặt các tiêu đề yêu cầu, trong số các tiêu đề khác

Mặc dù các đối số thứ hai và thứ ba là tùy chọn, nhưng thứ tự của chúng rất quan trọng. Axios sẽ luôn cho rằng đối số thứ hai là

const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');
6 mà bạn muốn gửi cùng với yêu cầu. Đó là một lỗi phổ biến khi chuyển đối tượng
const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');
7 làm đối số thứ hai thay vì đối số thứ ba

Để gửi biểu mẫu có axios trong Node. js, bạn phải lấy ranh giới của biểu mẫu và thêm nó vào yêu cầu

Phương thức

// Fetch external image as a stream
const response = await axios.get('https://i.imgur.com/8uJcFxW.jpg', { responseType: 'stream' });

const form = new FormData();
// Pass image stream from response directly to form
form.append('image', response.data, 'kitten.jpg');
0 trên biểu mẫu trả về một đối tượng có tiêu đề
// Fetch external image as a stream
const response = await axios.get('https://i.imgur.com/8uJcFxW.jpg', { responseType: 'stream' });

const form = new FormData();
// Pass image stream from response directly to form
form.append('image', response.data, 'kitten.jpg');
1 được đặt thành
// Fetch external image as a stream
const response = await axios.get('https://i.imgur.com/8uJcFxW.jpg', { responseType: 'stream' });

const form = new FormData();
// Pass image stream from response directly to form
form.append('image', response.data, 'kitten.jpg');
2 cộng với một ranh giới duy nhất

$ node product.js
{
    "meta": {
        "count": 32,
        "limit": 10,
        "page": 1,
        "next_url": "/shop/products/?page=2&limit=10"
    },
    "products": [
        {
            "name": "Bananas",
            "product_url": "/shop/products/3"
        },
        {
            "name": "Oranges",
            "product_url": "/shop/products/10"
        },
        {
            "name": "Pineapples",
            "product_url": "/shop/products/33"
        },
        {
            "name": "Dried Pineapples",
            "product_url": "/shop/products/42"
        },
        {
            "name": "Cranberries",
            "product_url": "/shop/products/57"
        },
        {
            "name": "Mango fresh",
            "product_url": "/shop/products/62"
        },
        {
            "name": "Raspberries",
            "product_url": "/shop/products/90"
        },
        {
            "name": "Cherries",
            "product_url": "/shop/products/7"
        },
        {
            "name": "Apple",
            "product_url": "/shop/products/18"
        },
        {
            "name": "Green Grapes",
            "product_url": "/shop/products/11"
        }
    ]
}
0

Khi bạn tạo một phiên bản biểu mẫu, bên trong nó sẽ tạo và sử dụng một ranh giới duy nhất. Nếu bạn đặt tiêu đề Loại nội dung với một ranh giới ngẫu nhiên mà bạn đã tạo, nó sẽ không khớp với ranh giới của biểu mẫu và yêu cầu sẽ không phân tích cú pháp chính xác. Do đó, hãy đảm bảo luôn sử dụng ranh giới của biểu mẫu

Sử dụng phép gán phá hủy để đặt tiêu đề Loại nội dung trong tham số

const form = new FormData();

// File parsed by multer from incoming request
const file = req.file;
form.append('file', file.buffer, file.originalname);

// or read from disk
const file = await fs.readFile('./my-image.jpg');
form.append('file', file, 'my-image.jpg');
7 (đối số thứ 3). Điều này cho phép bạn thêm các tiêu đề bổ sung nếu bạn muốn làm như vậy

Đây là cách gửi biểu mẫu với axios

$ node product.js
{
    "meta": {
        "count": 32,
        "limit": 10,
        "page": 1,
        "next_url": "/shop/products/?page=2&limit=10"
    },
    "products": [
        {
            "name": "Bananas",
            "product_url": "/shop/products/3"
        },
        {
            "name": "Oranges",
            "product_url": "/shop/products/10"
        },
        {
            "name": "Pineapples",
            "product_url": "/shop/products/33"
        },
        {
            "name": "Dried Pineapples",
            "product_url": "/shop/products/42"
        },
        {
            "name": "Cranberries",
            "product_url": "/shop/products/57"
        },
        {
            "name": "Mango fresh",
            "product_url": "/shop/products/62"
        },
        {
            "name": "Raspberries",
            "product_url": "/shop/products/90"
        },
        {
            "name": "Cherries",
            "product_url": "/shop/products/7"
        },
        {
            "name": "Apple",
            "product_url": "/shop/products/18"
        },
        {
            "name": "Green Grapes",
            "product_url": "/shop/products/11"
        }
    ]
}
2

Chỉ cần đặt tiêu đề Loại nội dung theo cách thủ công trong phần phụ trợ. Ở giao diện người dùng, trình duyệt sẽ tự động thực hiện việc này cho bạn, vì vậy bạn không nên tự đặt Loại nội dung nếu không tệp sẽ không tải lên đúng cách

Tóm lại, tải lên một tệp có axios trong Node. js yêu cầu bạn làm hai việc quan trọng

  1. Tạo biểu mẫu với thư viện dữ liệu biểu mẫu
  2. Lấy tiêu đề Loại nội dung có ranh giới của biểu mẫu với
    // Fetch external image as a stream
    const response = await axios.get('https://i.imgur.com/8uJcFxW.jpg', { responseType: 'stream' });
    
    const form = new FormData();
    // Pass image stream from response directly to form
    form.append('image', response.data, 'kitten.jpg');
    4 và gán nó cho yêu cầu axios

Chúng tôi đã xem xét các cách khác nhau để chuyển một tệp thành một biểu mẫu, dưới dạng Bộ đệm hoặc Luồng. Dưới đây là một ví dụ hoàn chỉnh đọc tệp từ đĩa vào Bộ đệm và tải nó lên API bên ngoài bằng axios

$ node product.js
{
    "meta": {
        "count": 32,
        "limit": 10,
        "page": 1,
        "next_url": "/shop/products/?page=2&limit=10"
    },
    "products": [
        {
            "name": "Bananas",
            "product_url": "/shop/products/3"
        },
        {
            "name": "Oranges",
            "product_url": "/shop/products/10"
        },
        {
            "name": "Pineapples",
            "product_url": "/shop/products/33"
        },
        {
            "name": "Dried Pineapples",
            "product_url": "/shop/products/42"
        },
        {
            "name": "Cranberries",
            "product_url": "/shop/products/57"
        },
        {
            "name": "Mango fresh",
            "product_url": "/shop/products/62"
        },
        {
            "name": "Raspberries",
            "product_url": "/shop/products/90"
        },
        {
            "name": "Cherries",
            "product_url": "/shop/products/7"
        },
        {
            "name": "Apple",
            "product_url": "/shop/products/18"
        },
        {
            "name": "Green Grapes",
            "product_url": "/shop/products/11"
        }
    ]
}
5

Làm thế nào để bạn tải lên một tập tin trong Node. js?

Sử dụng hướng dẫn phân tích cú pháp yêu cầu MIỄN PHÍ này và triển khai Node hoạt động liền mạch. js API tuân theo các phương pháp hay nhất mới nhất

Axios có tốt cho NodeJ không?

Nó dựa trên lời hứa, được sử dụng rộng rãi trong JavaScript và có cú pháp đơn giản. Hơn nữa, cho dù bạn đang làm việc ở mặt trước hay mặt sau, Axios đều cực kỳ hữu ích. Axios có thể tích hợp với NodeJ và các khung giao diện người dùng JavaScript như React, Vue và Angular .

Tại sao Axios tốt hơn tìm nạp?

Các thuộc tính khác nhau được sử dụng cho một yêu cầu gửi dữ liệu đến điểm cuối - Axios sử dụng thuộc tính dữ liệu, trong khi với tìm nạp, chúng tôi sử dụng thuộc tính body. We need to serialize data into a JSON string to send data. Axios automatically stringifies data when sending JavaScript objects to the API using the POST method.

Tôi có thể sử dụng Axios trên chương trình phụ trợ không?

Axios được hỗ trợ bởi tất cả các trình duyệt chính. Gói này có thể được sử dụng cho máy chủ phụ trợ của bạn , được tải qua CDN hoặc được yêu cầu trong ứng dụng giao diện người dùng của bạn.

Axios là gì?

Axios (cách điệu là ΛXIOS) là một trang web tin tức của Mỹ có trụ sở tại Quận Arlington, Virginia. Nó được thành lập vào năm 2016 và ra mắt vào năm sau bởi các cựu nhà báo Politico Jim VandeHei, Mike Allen và Roy Schwartz