質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
MongoDB

MongoDBはオープンソースのドキュメント指向データベースの1つです。高性能で、多くのリトルエンディアンシステムを利用することができます。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Q&A

0回答

789閲覧

クライアントからNode.jsにリクエストしたときだけコネクトできない

aiai8976

総合スコア112

MongoDB

MongoDBはオープンソースのドキュメント指向データベースの1つです。高性能で、多くのリトルエンディアンシステムを利用することができます。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

0グッド

1クリップ

投稿2019/08/01 02:31

編集2022/01/12 10:55

前提・実現したいこと

MongoDBにアクセスして、指定のオブジェクトをクライアントに返したいのですが、app.jsとして、MongoDBにアクセスし、オブジェクトを取得することはできました。
しかし、Node.jsの処理の一部としたときにMongoDBにconnectすることができません。
どういうことでしょうか。
わかる方がいましたら、コメントお願いします。

発生している問題・エラーメッセージ

コネクトに入っていないことが分かると思います。

hasegawa@hasegawa-W76OC:~/デスクトップ/akiyama/Node.js$ sudo node webServer.js Server running at http://localhost:80/ / /js/three.js-master/build/three.min.js /js/OrbitControls.js /get_value レスポンス _http_outgoing.js:595 throw new ERR_INVALID_ARG_TYPE('first argument', ^ TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type undefined at write_ (_http_outgoing.js:595:11) at ServerResponse.write (_http_outgoing.js:567:10) at Object.getValue (/home/hasegawa/デスクトップ/akiyama/Node.js/webServer.js:104:17) at Server.<anonymous> (/home/hasegawa/デスクトップ/akiyama/Node.js/webServer.js:128:29) at Server.emit (events.js:198:13) at parserOnIncoming (_http_server.js:677:12) at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)

該当のソースコード

app.js

const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'study'; //結果 var value; const client = new MongoClient(url,{useNewUrlParser: true}); // Use connect method to connect to the server client.connect(function(err) { assert.equal(null, err); console.log("Connected correctly to server"); const db = client.db(dbName); findDocuments(db, function() { client.close(); }); }); const findDocuments = function(db, callback) { // Get the documents collection const collection = db.collection('user'); // Find some documents collection.find({}).toArray(function(err, docs) { assert.equal(err, null); console.log("Found the following records"); //for (var document of docs) { //console.log("Found the following records"); //console.log(document[dist]); //console.log(document[rot]); //result=push(document.dist); //result=push(document.rot); //} console.log(docs); callback(docs); }); }

webServer.js

// 必要なファイルを読み込み var http = require('http'); var url = require('url'); var fs = require('fs'); var server = http.createServer(); // http.createServerがrequestされたら、(イベントハンドラ) server.on('request', function (req, res) { // Responseオブジェクトを作成し、その中に必要な処理を書いていき、条件によって対応させる var Response = { "renderHTML": function () { var template = fs.readFile('./template/index.html', 'utf-8', function (err, data) { // HTTPレスポンスヘッダを出力する res.writeHead(200, { 'content-Type': 'text/html' }); // HTTPレスポンスボディを出力する res.write(data); res.end(); }); }, "getThree": function () { var template = fs.readFile('./js/three.js-master/build/three.min.js', 'utf-8', function (err, data) { // HTTPレスポンスヘッダを出力する res.writeHead(200, { 'content-Type': 'text/javascript' }); // HTTPレスポンスボディを出力する res.write(data); res.end(); }); }, "getOrbit": function () { var template = fs.readFile('./js/OrbitControls.js', 'utf-8', function (err, data) { // HTTPレスポンスヘッダを出力する res.writeHead(200, { 'content-Type': 'text/javascript' }); // HTTPレスポンスボディを出力する res.write(data); res.end(); }); }, "getValue": function () { const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'study'; //結果 var value; const client = new MongoClient(url,{useNewUrlParser: true}); // Use connect method to connect to the server client.connect(function(err) { assert.equal(null, err); console.log("Connected correctly to server"); const db = client.db(dbName); findDocuments(db, function() { client.close(); }); }); const findDocuments = function(db, callback) { console.log("OK"); // Get the documents collection const collection = db.collection('user'); // Find some documents collection.find({}).toArray(function(err, docs) { assert.equal(err, null); console.log("Found the following records"); //for (var document of docs) { //console.log("Found the following records"); //console.log(document[dist]); //console.log(document[rot]); //result=push(document.dist); //result=push(document.rot); //} console.log(docs); callback(docs); }); } // HTTPレスポンスヘッダを出力する res.writeHead(200, { 'content-Type': 'text/html' }); console.log("レスポンス"); //console.log(result); // HTTPレスポンスボディを出力する res.write(value); res.end(); } }; // urlのpathをuriに代入 var uri = url.parse(req.url).pathname; console.log(uri); // URIで行う処理を分岐させる if (uri === "/") { // URLが「http://localhost:8080/」の場合、"renderHTML"の処理を行う Response["renderHTML"](); return; } else if (uri === "/js/three.js-master/build/three.min.js") { // URLが「http://localhost:8080/js/three.js-master/build/three.min.js」の場合、"getThree"の処理を行う Response["getThree"](); return; } else if (uri === "/js/OrbitControls.js") { // URLが「http://localhost:8080/js/OrbitControls.js」の場合、"getOrbit"の処理を行う Response["getOrbit"](); return; } else if (uri === "/get_value") { // URLが「http://localhost:8080/get_value」の場合、"getThree"の処理を行う Response["getValue"](); return; }; }); // 指定されたポート(8080)でコネクションの受け入れを開始する server.listen(80); console.log('Server running at http://localhost:80/');

###試したこと
curl http://~/get_valueでクライアントからとサーバからアクセスしましたが、

Empty reply from server

となりました。

補足情報(FW/ツールのバージョンなど)

OS:ubuntu
mongodb:4.0.10

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kabao

2019/08/12 08:52

似たような投稿をせず、整理してください。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問