我对节点非常陌生,并且已经查找了如何简单地设置节点服务器。我觉得我已经正确设置了它,但当我去https://localhost:8080/它说'#34;网站无法到达"。没有任何东西是控制台记录。我已经经历了许多类似的问题,但还没有解决方案帮助过我。我运行了npm init和npm install,这是我的代码:
var Express = require('express');
var Https = require('https');
var Fs = require('fs');
var app = Express();
var port = process.env.EXPRESS_PORT || 8080;
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
console.log("helloo?");
express.createServer(options, function (req, res) {
console.log("hi")
res.writeHead(200);
res.end("hello world\n");
}).listen(8080);
答案 0 :(得分:1)
代码中存在许多拼写错误,为了使其正常工作,我已经完成了更改。
要创建https服务器,您必须使用内置的node.js https
模块并通过传递证书创建https
服务器,如下所示
GoTo - https://localhost:8080/
回应:
{
message: "this is served in https"
}
var express = require('express');
var https = require('https');
var fs = require('fs');
var app = express();
var port = process.env.EXPRESS_PORT || 8080;
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
}
console.log("helloo?");
app.get('/', function(req, res) {
res.json({
message: 'this is served in https'
})
})
var secure = https.createServer(options, app); // for express
secure.listen(port, function() {
console.log('localhost started on', port)
})
// for just node server request listener
/* https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(port); */
答案 1 :(得分:0)
我为你写了一个基本代码。我认为这对你和你的答案都有用。试试这个。其他的事情是,如果你使用快递,那么无需导入http模块连接到服务器。我已经评论了一些代码,逐一尝试。
var express = require('express');
var app = express();
const fs = require('fs');
//const http = require('http');
app.set('port',process.env.PORT || 3000);
app.get('/',function(req, res){
res.send('Hellow World');
});
const fileName = __dirname + '/test.txt';
fs.readFile(fileName, (err, data) => {
if (err) {
console.error(err);
}console.log('Done!');
console.log(data.toString());
});
//or
/*
const data = fs.readFileSync(fileName);
console.log(data.toString());
*/
//below code will print whatever characters inside test.txt into test-copy.txt file
/*
const filename = __dirname + '/test.txt';
const outFileName = __dirname + '/test-copy.txt';
const readStream = fs.createReadStream(filename);
const writeStream = fs.createWriteStream(outFileName);
readStream.pipe(writeStream);
readStream.on('data', data => {
console.log(data.toString());
});
*/
app.listen(app.get('port'), function(){
console.log('Server listenning at port 3000');
});

首先,您必须创建test.txt文件并在其中写入内容。如果您尝试注释代码,请创建tezt-copy.txt文件。