クライアントサイドのhtmlからnode.jsを起動できない
Webアプリでローカル上のファイルをサーバーにアップロード後、ローカルのファイルをリネームしたい要件があり、セキュリティ上は望ましくないとは思いながら、調べていくうちに、node.jsなら出来なくもないという情報を得て、触ったこともないnode.jsをインストールして簡単なアプリを作成してみたのですが、呼び出すことすら出来ずに行き詰っています。
環境の問題なのか、書き方の問題なのかもよく判らず、識者のアドバイスが頂ければ幸いです。
前提
ファイルのリネームの実装はさておき、クライアントサイドのJavascriptからパラメタを与えて、node.jsを動かすところから始めました。
- 呼出元ページ:g:\myweb\node\index.html
- 呼出先スクリプト:g:\myweb\node\server.js
- node.jsのインストール先 g:\node
set path = g:\node
set NODE_PATH=g:\node\modules
発生している問題・エラーメッセージ
- サービスの起動 g:\myweb\server>node server.js
- サーバーがポート3000で実行中.....
- ページの起動 http://myserver/myweb/node/index.html
-
ページは正常に表示されるが、ボタン押下により、server.jsを呼び出したところ、エラーが出る。
-
エラー
-
GET http://192.168.1.244/node/myendpoint 404 (Not Found) Syntax error : Unexpected token '<', "<!DOCTYPE "... is not valid JSON
該当のソースコード
呼出元ページ [index.html]
html
1<html> 2<head> 3 <title>サーバーサイド呼び出し</title> 4</head> 5<body> 6 <button id="callServer">サーバーサイドを呼び出す</button> 7 <div id="response"></div> 8 9 <script> 10 const callServerButton = document.getElementById('callServer'); 11 const responseDiv = document.getElementById('response'); 12 13 callServerButton.addEventListener('click', () => { 14 // サーバーにGETリクエストを送信 15 fetch('/node/myendpoint') 16 .then(response => response.json()) 17 .then(data => { 18 // サーバーからのレスポンスを表示 19 responseDiv.textContent = 'サーバーからのレスポンス: ' + data.message; 20 }) 21 .catch(error => { 22 console.error('エラー:' + error); 23 }); 24 }); 25 </script> 26</body> 27</html> 28
呼出先スクリプト [server.js]
Javascript
1const http = require('http'); 2 3const server = http.createServer((req, res) => { 4 if (req.method === 'GET' && req.url === '/node/myendpoint') { 5 // クライアントからのGETリクエストを処理 6 const responseData = { message: 'サーバーサイドからのレスポンス' }; 7 res.setHeader('Content-Type', 'application/json'); 8 res.end(JSON.stringify(responseData)); 9 } else { 10 res.statusCode = 404; 11 res.end('Not Found'); 12 } 13}); 14 15const PORT = 3000; 16server.listen(PORT, () => { 17 console.log('サーバーがポート ' + PORT + 'で実行中...'); 18}); 19
試したこと
myweb/nodeの中ではなく、myweb/の直下に配置し、ソースも書き換えてみましたが、結果は同じでした。
(ページは表示されるも同じエラーメッセージ)
GET http://myweb/myendpoint 404 (Not Found)
該当のソースコード
呼出元ページ [index.html]
html
1 // サーバーにGETリクエストを送信 2 fetch('/myendpoint')
呼出先スクリプト [server.js]
Javascript
1 if (req.method === 'GET' && req.url === '/myendpoint') {
補足情報(FW/ツールのバージョンなど)
サーバーはWindows2019 で Apacheは2.4, node.jsはを使用しています。
クライアントはWindows10でブラウザはchromeを使用しています。

回答2件
あなたの回答
tips
プレビュー