gpt4 book ai didi

javascript - Node js上的简单服务器

转载 作者:可可西里 更新时间:2023-11-01 10:05:25 26 4
gpt4 key购买 nike

大家好 :) 我的问题是 response.vrite () 不工作为什么 ?还有一个问题。每次启动/升级页面都会调用db.open吗?

var http = require("http");
var Db = require ("mongodb").Db;
var Server = require("mongodb").Server;
function start () {
'use strict';
function onRequest (request, response) {
'use strict';
var db = new Db ("TestApp", new Server ("127.0.0.1", 27017, {}));
response.writeHead(200, {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"});
db.open (function (err, db, response) {
db.collection ('ObjectCollection', function (err, collection) {
collection.find().toArray (function (err, docs) {
console.log (docs);
response.write(JSON.stringify(docs));
});
});
});
response.end();
}

http.createServer(onRequest).listen(8080);
console.log ('Server has started...')
}exports.start = start;

最佳答案

您在 response.write 之前调用了 response.end。像这样在回调中移动 response.end 调用:

var http = require("http");
var Db = require ("mongodb").Db;
var Server = require("mongodb").Server;
function start () {
'use strict';
function onRequest (request, response) {
'use strict';
var db = new Db ("TestApp", new Server ("127.0.0.1", 27017, {}));
response.writeHead(200, {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"});
db.open (function (err, db, response) {
db.collection ('ObjectCollection', function (err, collection) {
collection.find().toArray (function (err, docs) {
console.log (docs);
response.write(JSON.stringify(docs));
response.end();
});
});
});
}

http.createServer(onRequest).listen(8080);
console.log ('Server has started...')
}
exports.start = start;

是的,每个请求都会打开一个新的 Db 对象,因此最好在启动期间打开一次。

关于javascript - Node js上的简单服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13666678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com