我的应用程序在端口 3030 上运行良好。我创建了一个名为"config"的新服务,并尝试通过 REST API 显示内容文件: 我更改了此服务文件中的默认 GET 方法,如下所示:
'use strict';
const hooks = require('./hooks');
const fs = require('fs');
const path = require('path');
const filename = path.join(__dirname, '..', '..', '..', 'public');
class Service {
constructor(options) {
this.options = options || {};
}
find(params) {
return Promise.resolve([]);
}
get(id, params) {
var file = fs.readFileSync(filename + '/player/' + id + '/config.txt', 'utf8', (err, data) => {
if (err) throw err;
var json = JSON.parse(data);
return Promise.resolve(json);
});
}
create(data, params) {
if(Array.isArray(data)) {
return Promise.all(data.map(current => this.create(current)));
}
return Promise.resolve(data);
}
update(id, data, params) {
return Promise.resolve(data);
}
patch(id, data, params) {
return Promise.resolve(data);
}
remove(id, params) {
return Promise.resolve({ id });
}
}
module.exports = function() {
const app = this;
// Initialize our service with any options it requires
app.use('/configs', new Service());
// Get our initialize service to that we can bind hooks
const configService = app.service('/configs');
// Set up our before hooks
configService.before(hooks.before);
// Set up our after hooks
configService.after(hooks.after);
};
module.exports.Service = Service;
我没有收到错误,但它不起作用。打开网址后 http://127.0.0.1/configs/80866 我的页面一直在加载。怎么了?
您正在调用readFileSync
它同步读取文件,但传递异步回调(可能永远不会被调用)。在该回调中返回 Promise,但不在服务方法中返回。get
必须看起来像这样:
get(id, params) {
return new Promise((resolve, reject) => {
const file = path.join(filename, 'player', id, config.txt);
fs.readFile(file, (error, data) => {
if(error) {
return reject(error);
}
const json = JSON.parse(data.toString());
resolve(json);
});
});
}