Node.js TLS“TypeError:无法读取未定义的属性'indexOf'”

时间:2016-03-21 02:14:09

标签: node.js ssl express

我使用nodejs 5.9.0并表达。在我的代码中,我以这种方式创建服务器:

var app = express();

var tls = require('tls');
var fs = require('fs');
var options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};
tls.createServer(options, app).listen(3000);

var http = require('http');
http.createServer(app).listen(80);

HTTP工作正常。但是当我尝试访问https://localhost:3000时,它会抛出异常:

C:\src\nodejs\videos\node_modules\express\lib\router\index.js:140
  var search = 1 + req.url.indexOf('?');
                          ^

TypeError: Cannot read property 'indexOf' of undefined
    at Function.handle (C:\src\nodejs\videos\node_modules\express\lib\router\index.js:140:27)
    at EventEmitter.handle (C:\src\nodejs\videos\node_modules\express\lib\application.js:173:10)
    at Server.app (C:\src\nodejs\videos\node_modules\express\lib\express.js:38:9)
    at emitOne (events.js:90:13)
    at Server.emit (events.js:182:7)
    at TLSSocket.<anonymous> (_tls_wrap.js:817:14)
    at emitNone (events.js:80:13)
    at TLSSocket.emit (events.js:179:7)
    at TLSSocket._init.ssl.onclienthello.ssl.oncertcb.TLSSocket._finishInit (_tls_wrap.js:593:8)
    at TLSSocket.onhandshakedone (_tls_wrap.js:65:8)
 Program node bin/www exited with code 1

我是否使用了nodejs TLS并表达了正确的方法?

1 个答案:

答案 0 :(得分:3)

您需要对Express应用使用https,而不是tls,因为tls基本上只是普通的TCP连接(由TLS保护):

var app = express();

var fs = require('fs');
var http = require('http');
var https = require('https');

var options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, app).listen(3000);
http.createServer(app).listen(80);