<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國際加速解決方案。 廣告
                # Node HTTP 教程 > 原文: [http://zetcode.com/javascript/http/](http://zetcode.com/javascript/http/) Node HTTP 教程展示了如何使用帶有 HTTP 模塊的 JavaScript 創建 HTTP 服務器和客戶端應用。 ## HTTP HTTP 是一個 Node.js 模塊,可用于在 JavaScript 中創建 HTTP 服務器和客戶端應用。 流行的 JavaScript 框架(包括 Express 和 HapiJS)建立在 HTTP 模塊的頂部。 本教程教您 HTTP 交互的基礎知識。 要創建真實的 Web 應用,我們應該使用完整的 Web 框架,例如 JavaScript 的 Express 或 PHP 的 Symfony。 ## 安裝 HTTP 首先,我們安裝 HTTP 模塊。 ```js $ node -v v11.5.0 ``` 我們使用 Node.js 11.5 版。 ```js $ npm init -y ``` 我們啟動一個新的 Node.js 應用。 ```js $ npm i http ``` 我們使用`npm i http`命令安裝 HTTP。 ## Node HTTP 簡單服務器 使用`createServer()`創建服務器應用。 `simple.js` ```js const http = require('http'); http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('Hello there'); res.end(); }).listen(8080); console.log('server running on port 8080'); ``` 該示例創建了一個非常簡單的 HTTP 服務器,該服務器將文本消息發送到客戶端。 服務器在端口 8080 上運行。 ```js const http = require('http'); ``` 首先,我們包括 HTTP 模塊。 ```js http.createServer((req, res) => { ``` 我們使用`createServer()`函數創建一個 Web 應用。 它接受一個接收兩個參數的處理函數:請求和響應對象。 ```js res.writeHead(200, { 'Content-Type': 'text/plain' }); ``` 使用`writeHead()`方法,我們將標頭寫入響應。 我們指定狀態碼和內容類型。 ```js res.write('Hello there'); ``` 我們將數據寫入響應。 ```js res.end(); ``` 我們將回復發送給客戶。 ```js $ node simple.js server running on port 8080 ``` 我們啟動服務器。 ```js $ curl localhost:8080 Hello there ``` 使用`curl`工具,我們向服務器創建 GET 請求并接收消息。 ## Node HTTP 發送 JSON 在下一個示例中,我們創建一個發送 JSON 響應的服務器。 JSON(JavaScript 對象表示法)是一種輕量級的數據交換格式。 `send_json.js` ```js const http = require('http'); const server = http.createServer((req, res) => { if (req.url == '/now') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.write(JSON.stringify({ now: new Date() })); res.end(); } else { res.end('Invalid request'); } }); server.listen(8080); console.log('server running on port 8080'); ``` 應用通過以 JSON 發送當前日期來響應`/now`請求路徑。 ```js if (req.url == '/now') { ``` 我們檢查請求 URL 是否等于`/now`。 ```js res.writeHead(200, { 'Content-Type': 'application/json' }); ``` 我們通知客戶端,我們在標頭中使用適當的內容類型發送 JSON 響應。 ```js res.write(JSON.stringify({ now: new Date() })); ``` 我們將 JSON 中的當前日期寫入響應中。 ## Node HTTP 發送 HTML 接下來,我們將向客戶端發送 HTML 數據。 `send_html.js` ```js const http = require('http'); const server = http.createServer(function (req, res) { if (req.url == '/') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<html><body><p>This is home page.</p></body></html>'); res.end(); } else if (req.url == "/contact") { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<html><body><p>This is contact page</p></body></html>'); res.end(); } else if (req.url == "/admin") { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<html><body><p>This is admin page</p></body></html>'); res.end(); } else { res.end('Invalid request'); } }); server.listen(8080); console.log('server running on port 8080'); ``` 我們指定`text/html`內容類型,并將 HTML 標記寫入響應。 > **注意**:在實際應用中,我們不會在響應中編寫 HTML 代碼。 我們使用模板。 ## Node HTTP 查詢參數 客戶端可以通過向 URL 添加查詢參數來與服務器通信。 `query_params.js` ```js const http = require('http'); const url = require('url'); http.createServer((req, res) => { let q = url.parse(req.url, true).query; let msg = `${q.name} is ${q.age} years old`; res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write(msg); res.end(); }).listen(8080); console.log('server running on port 8080'); ``` 在該示例中,服務器以根據查詢參數構建的消息作為響應。 ```js const url = require('url'); ``` 為了解析查詢參數,我們使用`url`模塊。 ```js let q = url.parse(req.url, true).query; ``` 我們得到具有值的查詢對象。 ```js let msg = `${q.name} is ${q.age} years old`; ``` 我們根據查詢參數構建消息。 ```js $ curl "localhost:8080/?name=Peter&age=34" Peter is 34 years old ``` 啟動服務器后,我們使用`curl`創建請求。 我們指定查詢參數。 ## Node HTTP 服務器 下面的示例創建一個更復雜的 HTTP 服務器。 `docs`子目錄中有三個 HTML 文件。 `docs/about.html` ```js <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>About page</title> </head> <body> <p>This is about page.</p> </body> </html> ``` 這是`about.html`文件。 `docs/contact.html` ```js <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Contact page</title> </head> <body> <p>This is contact page.</p> </body> </html> ``` 這是`contact.html`文件。 `docs/index.html` ```js <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home page</title> </head> <body> <p> This is home page. </p> </body> </html> ``` 這是`index.html`文件。 `http_server.js` ```js const http = require('http'); const fs = require('fs'); const url = require('url'); const server = http.createServer((req, res) => { let pathname = url.parse(req.url).pathname; console.log(`Request for ${pathname} received`); if (pathname == '/') { pathname = '/index.html'; } fs.readFile('docs/' + pathname.substr(1), (err, data) => { if (err) { console.error(err); res.writeHead(404, { 'Content-Type': 'text/plain' }); res.write('404 - file not found'); } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(data.toString()); } res.end(); }); }); server.listen(8080); console.log('server running on port 8080'); ``` ```js const fs = require('fs'); ``` 我們使用`fs`模塊讀取 HTML 文件。 該示例從文件系統讀取 HTML 文件。 ```js let pathname = url.parse(req.url).pathname; ``` 我們確定路徑名,即要加載的文件名。 ```js if (pathname == '/') { pathname = '/index.html'; } ``` 對于根頁面,我們發送`index.html`。 ```js fs.readFile('docs/' + pathname.substr(1), (err, data) => { ``` 使用`readFile()`方法,我們讀取 HTML 文件的內容。 ```js if (err) { console.error(err); res.writeHead(404, { 'Content-Type': 'text/plain' }); res.write('404 - file not found'); } ... ``` 發生錯誤時,我們會將 404 代碼發送給客戶端。 ```js } else { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write(data.toString()); } ``` 如果找到并讀取了文件,我們會將文件的內容發送給客戶端。 ## Node HTTP GET 請求 我們也可以使用 HTTP 模塊來創建客戶端請求。 `http_get.js` ```js const http = require('http'); const options = { hostname: 'webcode.me', port: 80, path: '/', method: 'GET' }; const req = http.request(options, (res) => { console.log(`statusCode: ${res.statusCode}`); res.on('data', (d) => { process.stdout.write(d); }); }); req.on('error', (err) => { console.error(err); }); req.end(); ``` 該示例向`webcode.me`創建 HTTP GET 請求。 ```js const options = { hostname: 'webcode.me', port: 80, path: '/', method: 'GET' }; ``` 這些選項包含所生成請求的主機名,端口,路徑和 HTTP 方法。 ```js const req = http.request(options, (res) => { ``` 使用`request()`生成請求。 ```js res.on('data', (d) => { process.stdout.write(d); }); ``` 我們不斷將傳入的數據寫入數據事件處理器中的控制臺。 ```js $ node http_get.js statusCode: 200 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <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> ``` 這是輸出。 另外,我們可以使用`get()`方法。 `http_get.js` ```js const http = require('http') const req = http.get({ host: 'webcode.me', path: '/' }, (res) => { // Continuously update stream with data let content = ''; res.on('data', (chunk) => { content += chunk; }); res.on('end', () => { console.log(content); }); }); req.end(); ``` 我們生成對同一網站的 GET 請求。 ```js // Continuously update stream with data let content = ''; res.on('data', (chunk) => { content += chunk; }); ``` 我們不斷將檢索到的數據塊添加到`content`變量中。 ```js res.on('end', () => { console.log(content); }); ``` 最后,我們將變量打印到控制臺。 ## Node HTTP POST 請求 下面的示例向`httpbin.org`網站創建 POST 請求。 這是一個免費的網站,我們可以在其中測試我們的請求。 由于站點使用 HTTPS 協議,因此我們使用`https`模塊。 `http_post.js` ```js const https = require('https'); let payload = JSON.stringify({ "name": "Peter", "age": 34 }); let headers = { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload, 'utf8') }; let options = { host: 'httpbin.org', port: 443, path: '/post', method: 'POST', headers: headers }; let reqPost = https.request(options, (res) => { console.log("status code: ", res.statusCode); res.on('data', (chunks) => { process.stdout.write(chunks); }); }); reqPost.write(payload); reqPost.end(); reqPost.on('error', (err) => { console.error(err); }); ``` 該示例將數據發送到測試網站。 服務器以包含我們已發送的有效負載的數據進行響應。 ```js const https = require('https'); ``` 我們使用`https`模塊。 ```js payload = JSON.stringify({ "name": "Peter", "age": 34 }); ``` 這是要發送的有效負載。 ```js let headers = { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload, 'utf8') }; ``` 這些是標題。 我們發送 JSON 數據。 我們指定內容的長度。 ```js let options = { host: 'httpbin.org', port: 443, path: '/post', method: 'POST', headers: headers }; ``` 這些是 POST 請求的選項。 HTTPS 標準端口為 443。 ```js let reqPost = https.request(options, (res) => { console.log("status code: ", res.statusCode); res.on('data', (chunks) => { process.stdout.write(chunks); }); }); ``` 在 post 調用的數據事件處理器中,我們將數據寫入控制臺。 ```js reqPost.write(payload); ``` 我們將有效載荷數據寫入 POST 請求。 ```js reqPost.end(); ``` 請求已發送。 在本教程中,我們使用了 JavaScript HTTP 模塊。 列出 [JavaScript 教程](/all/#js)。
                  <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>

                              哎呀哎呀视频在线观看