<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Axios 教程 > 原文: [http://zetcode.com/javascript/axios/](http://zetcode.com/javascript/axios/) Axios 教程展示了如何使用 Axios 客戶端庫在 JavaScript 中生成請求。 ## Axios Axios 是用于瀏覽器和 Node.js 的基于 Promise 的 HTTP 客戶端。 Axios 使向 REST 端點發送異步 HTTP 請求和執行 CRUD 操作變得容易。 它可以在普通 JavaScript 中使用,也可以與 Vue 或 React 之類的庫一起使用。 在本教程中,我們將在 Node.js 應用中使用 Axios。 ## 安裝 Axios 首先,我們安裝 Axios。 ```js $ node -v v11.5.0 ``` 我們使用 Node.js 11.5 版。 ```js $ npm init -y ``` 我們啟動一個新的 Node.js 應用。 ```js $ npm i axios ``` 我們使用`npm i axios`命令安裝 Axios。 ## Axios 響應對象 當我們向服務器發送請求時,它返回一個響應。 Axios 響應對象包括: * `data` - 服務器返回的有效負載 * `status` - 服務器返回的 HTTP 代碼 * `statusText` - 服務器返回的 HTTP 狀態消息 * `header` - 服務器發送的標頭 * `config` - 原始請求配置 * `request` - 請求對象 ## 帶回調的 Axios GET 請求 在第一個示例中,我們創建一個簡單的 GET 請求。 我們使用回調。 `simple_get.js` ```js const axios = require('axios'); axios.get('http://webcode.me').then(resp => { console.log(resp.data); }); ``` 我們生成一個簡單的 GET 請求并顯示輸出。 ```js const axios = require('axios'); ``` 包括 Axios 庫。 ```js axios.get('http://webcode.me').then(resp => { console.log(resp.data); }); ``` 使用`get()`,我們發送一個 GET 請求。 我們從響應中輸出數據。 數據是 HTML 代碼。 ```js $node simple_get.js <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>My html page</title> </head> <body> <p> Today is a beautiful day. We go swimming and fishing. </p> <p> Hello there. How are you? </p> </body> </html> ``` 這是輸出。 ## 帶有異步/等待的 Axios GET 請求 下面的示例創建相同的請求。 這次我們使用`async/await`語法。 `simple_get.js` ```js const axios = require('axios'); async function makeGetRequest() { let res = await axios.get('http://webcode.me'); let data = res.data; console.log(data); } makeGetRequest(); ``` 該示例使用`async/await`語法創建一個簡單的 GET 請求。 ## Axios HEAD 請求 HEAD 請求是沒有消息正文的 GET 請求。 在 Axios 中,使用`head()`創建 HEAD 請求。 `head_request.js` ```js const axios = require('axios'); async function makeHeadRequest() { let res = await axios.head('http://webcode.me'); console.log(`Status: ${res.status}`) console.log(`Server: ${res.headers.server}`) console.log(`Date: ${res.headers.date}`) } makeHeadRequest(); ``` 該示例顯示了通過 HEAD 請求生成的響應的狀態,服務器名稱,響應日期。 ```js $ node head_request.js Status: 200 Server: nginx/1.6.2 Date: Mon, 04 Feb 2019 15:08:56 GMT ``` 這是輸出。 ## Axios 基本 API `get()`,`post()`或`delete()`方法是基本 axios API 的便捷方法:`axios(config)`和`axios(url, config)`。 `basic_api.js` ```js const axios = require('axios'); async function makeRequest() { const config = { method: 'get', url: 'http://webcode.me' } let res = await axios(config) console.log(res.status); } makeRequest(); ``` 該示例向`webcode.me`創建 GET 請求。 ```js const config = { method: 'get', url: 'http://webcode.me' } ``` 我們在配置對象中指定請求的詳細信息。 ## Axios 自定義標頭 在下面的示例中,我們發送一個自定義標頭。 `custom_header.js` ```js const axios = require('axios'); async function makeRequest() { const config = { method: 'get', url: 'http://webcode.me', headers: { 'User-Agent': 'Console app' } } let res = await axios(config) console.log(res.request._header); } makeRequest(); ``` 該示例發送一個自定義的標頭。 ```js const config = { method: 'get', url: 'http://webcode.me', headers: { 'User-Agent': 'Console app' } } ``` 自定義數據將添加到配置對象的`headers`屬性中。 ```js console.log(res.request._header); ``` 我們驗證發送的數據。 ```js $ node custom_header.js GET / HTTP/1.1 Accept: application/json, text/plain, */* User-Agent: Console app Host: webcode.me Connection: close ``` 這是輸出。 ## 獲取 Github 信息 許多在線服務包含公共 API。 在以下示例中,我們生成對 Github API 的請求。 `github.js` ```js const axios = require('axios'); async function getNumberOfFollowers() { let res = await axios.get('https://api.github.com/users/janbodnar'); let nOfFollowers = res.data.followers; let location = res.data.location; console.log(`# of followers: ${nOfFollowers}`) console.log(`Location: ${location}`) } getNumberOfFollowers(); ``` 在示例中,我們獲得關注者的數量和用戶的位置。 ```js $ node github.js # of followers: 44 Location: Bratislava ``` 這是輸出。 ## Axios POST 請求 使用`post()`方法創建 POST 請求。 `post_request.php` ```js const axios = require('axios'); async function makePostRequest() { let res = await axios.post('https://jsonplaceholder.typicode.com/posts'); console.log(`Status code: ${res.status}`); console.log(`Status text: ${res.statusText}`); console.log(`Request method: ${res.request.method}`); console.log(`Path: ${res.request.path}`); console.log(`Date: ${res.headers.date}`); console.log(`Data: ${res.data}`); } makePostRequest(); ``` 該示例創建對在線測試服務的 POST 請求。 ```js $ node post_request.js Status code: 201 Status text: Created Request method: POST Path: /posts Date: Mon, 04 Feb 2019 16:54:36 GMT Data: [object Object] ``` 這是輸出。 ## Axios 下載圖像 以下示例顯示了如何使用 Axios 下載圖像。 `get_image.js` ```js const axios = require('axios'); const fs = require('fs'); var config = { responseType: 'stream' }; let url = 'httpsimg.dog.ceo/breeds/setter-english/n02100735_4870.jpg'; async function getImage() { let resp = await axios.get(url, config); resp.data.pipe(fs.createWriteStream('image.jpg')); } getImage(); ``` 該示例從在線服務中檢索圖像,該服務保留了狗的圖像。 ```js const axios = require('axios'); const fs = require('fs'); ``` 我們包括`axios`和`fs`模塊。 ```js var config = { responseType: 'stream' }; ``` 我們在配置對象中指定響應類型。 ```js let resp = await axios.get(url, config); ``` 我們得到圖像。 ```js resp.data.pipe(fs.createWriteStream('image.jpg')); ``` 借助`fs`模塊,我們將圖像保存到磁盤。 ## Axios 多個請求 我們可以使用 Axios 一次創建多個請求。 `multiple_requests.js` ```js const axios = require('axios'); async function makeRequests() { let [u1, u2] = await Promise.all([ axios.get('https://api.github.com/users/janbodnar'), axios.get('https://api.github.com/users/symfony') ]); console.log(`Jan Bodnar: ${u1.data.created_at}`); console.log(`Symfony: ${u2.data.created_at}`); } makeRequests(); ``` 要發送多個請求,我們使用`Promise.all()`方法。 ```js $ node multiple_requests.js Jan Bodnar: 2016-01-31T12:12:28Z Symfony: 2009-10-24T04:05:23Z ``` 這是輸出。 ## 將 Axios 與 JSON 服務器一起使用 JSONServer 是一個很棒的工具,它使我們能夠輕松創建偽造的 REST API。 ```js $ npm i -g json-server ``` 我們安裝`json-server`。 `users.json` ```js { "users": [ { "id": 1, "first_name": "Robert", "last_name": "Schwartz", "email": "rob23@gmail.com" }, { "id": 2, "first_name": "Lucy", "last_name": "Ballmer", "email": "lucyb56@gmail.com" }, { "id": 3, "first_name": "Anna", "last_name": "Smith", "email": "annasmith23@gmail.com" }, { "id": 4, "first_name": "Robert", "last_name": "Brown", "email": "bobbrown432@yahoo.com" }, { "id": 5, "first_name": "Roger", "last_name": "Bacon", "email": "rogerbacon12@yahoo.com" } ] } ``` 這是我們的測試數據。 ### 啟動 JSON 服務器 JSON 服務器從我們已全局安裝的`json-server`啟動。 ```js $ json-server --watch data.json ``` `--watch`選項用于指定服務器的數據。 ```js $ curl localhost:3000/users/2/ { "id": 2, "first_name": "Lucy", "last_name": "Ballmer", "email": "lucyb56@gmail.com" } ``` 使用 curl 命令,使用戶獲得 ID 2。 ## 發布用戶 我們發布了一個新用戶。 `post_user.js` ```js const axios = require('axios'); async function makePostRequest() { params = { id: 6, first_name: 'Fred', last_name: 'Blair', email: 'freddyb34@gmail.com' } let res = await axios.post('http://localhost:3000/users/', params); console.log(res.data); } makePostRequest(); ``` 該示例發布了一個新用戶。 ```js let res = await axios.post('http://localhost:3000/users/', params); ``` 將`post`參數作為第二個參數傳遞給`post()`方法。 ### 獲取用戶 我們從測試服務器獲取用戶。 `get_users.js` ```js const axios = require('axios'); async function makeGetRequest() { let res = await axios.get('http://localhost:3000/users/'); let data = res.data; console.log(data); } makeGetRequest(); ``` 該程序從我們的測試服務器檢索所有用戶。 ```js $ node get_users.js [ { id: 1, first_name: 'Robert', last_name: 'Schwartz', email: 'rob23@gmail.com' }, { id: 2, first_name: 'Lucy', last_name: 'Ballmer', email: 'lucyb56@gmail.com' }, { id: 3, first_name: 'Anna', last_name: 'Smith', email: 'annasmith23@gmail.com' }, { id: 4, first_name: 'Robert', last_name: 'Brown', email: 'bobbrown432@yahoo.com' }, { id: 5, first_name: 'Roger', last_name: 'Bacon', email: 'rogerbacon12@yahoo.com' }, { id: 6, first_name: 'Fred', last_name: 'Blair', email: 'freddyb34@gmail.com' } ] ``` 這是輸出。 ## 刪除用戶 使用`delete()`刪除資源。 `delete_user.js` ```js const axios = require('axios'); async function makePostRequest() { let res = await axios.delete('http://localhost:3000/users/2/'); console.log(res.status); } makePostRequest(); ``` 該示例刪除具有 ID 2 的用戶。 在本教程中,我們使用了 JavaScript Axios 模塊。 您可能也對以下相關教程感興趣: [JSON 服務器教程](/javascript/jsonserver/),[笑話教程](/javascript/jest/), [Moment.js 教程](/javascript/momentjs/),[從 JavaScript 中的 URL 讀取 JSON](/articles/javascriptjsonurl/) , [JavaScript 貪食蛇教程](/javascript/snake/), [JQuery 教程](/web/jquery/), [Node Sass 教程](/javascript/nodesass/), [Lodash 教程](/javascript/lodash/)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看