我正在尝试将NodeJS API部署到Heroku,而没有任何依赖,特别是没有Express的情况。
它在localhost
上可以正常工作,但是在Heroku上,它不能同时用于HTTP和HTTPS请求,因为在发出请求时给了我默认的应用程序错误页面。
我收到这个错误,使我对发生的一切一无所知:heroku logs --tail
heroku[router]: at=error code=H13 desc="Connection closed without response"
method=GET path="/usuarios?id=0" host=simple-rest-nodejs.herokuapp.com
request_id=29f65d75-6594-44f8-8f9d-6be025cd6ed6 fwd="179.223.167.29" dyno=web.1
connect=0ms service=1ms status=503 bytes=0 protocol=https
实时版本URL: https://simple-rest-nodejs.herokuapp.com
index.js代码:(实际上是API的整个代码)
const handlers = {};
const fs = require('fs');
const url = require('url');
const http = require('http');
const https = require('https');
handlers.status = function(data, callback) {
callback(202, {status: true});
};
handlers._usuarios = {};
handlers.usuarios = function(data, callback) {
fs.readFile('./libs/usuarios.json', 'utf8', function(err, usuarios) {
if (err) {
throw new Error(err);
} else {
const metodos = ['get'];
if(metodos.indexOf(data.method) > -1){
handlers._usuarios[data.method](usuarios, data, callback);
} else {
callback(405, {error: 405, message: "Método não permitido"});
}
}
});
};
handlers._usuarios.get = function(usuarios, data, callback) {
const array = JSON.parse(usuarios);
const id = typeof(data.queryParams.id) == 'string' ? data.queryParams.id : false;
if (id) {
callback(202, array.filter(function(usuario) {
return usuario.id.toString() === id;
}));
} else {
callback(202, array);
}
}
handlers.notFound = function(data, callback) {
callback(404, {error: 404});
};
const router = {
'': handlers.status,
'usuarios': handlers.usuarios,
};
/* REMOVE THE COMMENT TO RUN THIS ON LOCALHOST
const httpServer = http.createServer(function(req, res) {
server(req, res);
}).listen(process.env.PORT || 5000);
*/
httpsServerOptions = {
'key': fs.readFileSync('./https/key.pem'),
'cert': fs.readFileSync('./https/cert.pem')
};
const httpsServer = https.createServer(httpsServerOptions, function(req, res) {
server(req, res);
}).listen(process.env.PORT || 6000);
const server = function(req, res) {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname;
const trimmedPath = path.replace(/^\/+|\/+$/g, '');
const data = {
queryParams: parsedUrl.query,
method: req.method.toLowerCase()
};
const chosenHandler = typeof(router[trimmedPath]) !== 'undefined' ? router[trimmedPath] : handlers.notFound;
chosenHandler(data, function(statusCode, payload) {
res.writeHead(statusCode, {'Content-Type': 'application/json'});
res.write(JSON.stringify(payload));
res.end();
});
}
根本没有安装任何依赖项,也没有node_modules文件夹。 package.json
文件基本上为NodeJS设置项目元数据和启动脚本。
package.json:
{
"name": "simple-rest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [
"nodejs",
"javascript",
"js"
],
"author": "",
"license": ""
}
谢谢。