前提・実現したいこと
表題の通り、Node.jsを使って、サーバを立て、サイトを立ち上げる実装について
お伺いします。
結論、サーバを立ち上げても、サイトが立ち上がりません(htmlサイト)
恐れ入りますが、宜しくお願い致します
発生している問題・エラーメッセージ
問題: サーバーは建てたが、サイトが立ち上がらない。 エラー: 「このサイトにアクセスできませんlocalhost で接続が拒否されました。」
試したこと
npm run startで サーバー立ち上げました。
localhost: 3030で、Htmlが立ち上がるかと思いきや、立ち上がりません。
該当のソースコード
package.json
{ "name": "node-tutorial", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start" : "node server.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "http": "^0.0.1-security" } }
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>HTMLファイルです。</h1> </body> </html>
JS
const http = require("http"); const PORT = 3030; // node.jsで用意されているfsはファイルを読み込む。(readFile)Syncは非同期処理の意味 const html = require("fs").readFileSync("./index.html"); // Webサーバを作ろう const server = http.createServer((req, res) => { // res,reqはブラウザからアクセス。アクセスが来た処理↓ res.writeHead( // ステータスコード↓ 200, // タイプ {"Content-Type": "text/html"}); res.write(html); res.end(); }); // サーバを起動する server.listen(PORT, () => { console.log("server"); });

0 コメント