1

nodejs http サーバーを作成しました

var http = require("http");
var url = require("url");
var express = require('express');
var app = express();

function start(route, handle){
    function onRequest(request,response){
        var pathname = url.parse(request.url).pathname;
        console.log("Request for " + pathname + " received.");
        route(handle, pathname, response, request);
    }

    http.createServer(onRequest).listen(8888);
    console.log("Server has started");
    app.listen(8888);
    console.log('Express app listening on port 8888');
}

それはエラーを与える

f:\Labs\nodejs\webapp>node index.js
Server has started
Express app listening on port 8888

events.js:66
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: listen EADDRINUSE
    at errnoException (net.js:769:11)
    at Server._listen2 (net.js:909:14)
    at listen (net.js:936:10)
    at Server.listen (net.js:985:5)
    at Function.app.listen (f:\Labs\nodejs\webapp\node_modules\express\lib\appli
cation.js:532:24)
    at Object.start (f:\Labs\nodejs\webapp\server.js:15:6)
    at Object.<anonymous> (f:\Labs\nodejs\webapp\index.js:11:8)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)

app.listen のポートを変更すると、このエラーがスローされません。何ができますか?

サーバーポート以外のポートを変更すると、サーバーのセッションが別のポートに保持されますか??

また、他のjsページでこのアプリ変数にアクセスしてデータを取得/設定するにはどうすればよいですか?

4

2 に答える 2

3

同じポートで実行する場合は、現在実行中のノード プロセスがあるかどうかを確認できます。

ps aux | grep node

その後kill -9 PROCESSID

于 2013-03-25T02:09:05.633 に答える
2

このように同じポートで複数のものをリッスンすることはできないため、EADDRINUSEエラーが発生します。Express の使用中に独自の http サーバーを作成する場合は、次のように実行できます。

var express = require('express');
var https = require('https');
var http = require('http');
var app = express();

http.createServer(app).listen(8888);
https.createServer(options, app).listen(443);

Express ドキュメントから:

express() によって返されるアプリは実際には JavaScript 関数であり、リクエストを処理するためのコールバックとしてノードの http サーバーに渡されるように設計されています。

または、あなたはただすることができます

app.listen(8888);

次に、Express がhttpサーバーをセットアップします。

次に、受信するリクエストを実際に処理するために、Express でルートを設定します。Express では、ルートは次のようになります。

app.get('/foo/:fooId', function(req, res, next) {
   // get foo and then render a template
   res.render('foo.html', foo);
});

他のモジュール (通常はテスト用)にアクセスしたい場合はapp、他の変数と同じようにエクスポートできます。

module.exports.app = app;

require('./app').appその後、他のモジュールでできるようになります。

于 2012-09-22T16:31:48.670 に答える