我创建了一个http服务器,并且一切正常。
但是我实际上想创建一个https服务器。我不在乎安全性,因为这仅用于测试。
如何从https(而不是http)公开数据?
这很容易做到吗?知道我该如何轻松地做到这一点吗?
"use strict";
var http = require("http");
var fs = require("fs");
var port = 5050;
var cors = function cors(req, res) {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
};
var server = http.createServer(function(request, response) {
// simulate SEND to IPP Process
if(request.method === 'PUT') {
response.writeHead(200, { 'Content-Type': request.headers.accept });
response.end();
return;
}
if (request.headers.origin) {
cors(request, response);
}
var fileName = request.url.substr(request.url.lastIndexOf('/')+1);
if(fileName !== 'favicon.ico') {
fileName = fileName === 'inData' ? 'all' : fileName;
try {
response.writeHead(200, {'Content-Type': request.headers.accept});
var res = '';
if(request.headers.accept === 'application/xml') {
res = fs.readFileSync('mock/data/'+fileName+'.xml');
} else if (request.headers.accept === 'text/plain') {
res = fs.readFileSync('mock/data/'+fileName+'.txt');
} else {
if(fileName.indexOf('?') !== -1) {
fileName = fileName.substr(0, fileName.indexOf('?'));
}
res = fs.readFileSync('mock/data/'+fileName+'.json');
}
response.write(res);
} catch (e) {
console.warn(e.message);
response.writeHead(400, {});
}
response.end();
} else {
response.writeHead(400, {"Content-Type": "text/html"});
response.end();
}
});
server.listen(port);
console.log("Server is listening at http://localhost:"+port);