我正在 node.js 中构建一个 reddit API 包装器,以更加熟悉 js 和 node。到目前为止,这是我的代码:
./lib/reddit.js:
var request = require("request");
var reddit = function () {
var self = this,
userAgent = "node.js api wrapper",
debug = false,
uh = "",
cookie = "";
self.getJSON = function (url, callback) {
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body);
}
});
};
self.post = function (url, data, callback) {
request.post(url, { form: data }, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body);
}
});
};
};
reddit.prototype = {
login: function (username, password) {
var data = {
"user": username,
"password": password,
"rem": true
};
this.post("http://www.reddit.com/api/login", data, function (body) {
var response = JSON.parse(body);
this.uh = response.json.data.modhash;
this.cookie = response.json.data.cookie;
console.log(response);
console.log(this.uh);
console.log(this.cookie);
});
}
}
exports.reddit = reddit;
应用程序.js:
var reddit = require("./lib.reddit").reddit;
reddit.login("username", "password");
我收到此错误:
[jet@cowboybebop reddit]$ node app.js
/home/jet/projects/reddit/app.js:5
reddit.login("username", "password");
^
TypeError: Object function () {
var self = this,
userAgent = "node.js api wrapper",
debug = false,
uh = "",
cookie = "";
self.getJSON = function (url, callback) {
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body);
}
});
};
self.post = function (url, data, callback) {
request.post(url, { form: data }, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body);
}
});
};
} has no method 'login'
at Object.<anonymous> (/home/jet/projects/reddit/app.js:5:8)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
我最初的登录功能定义为
reddit.prototype.login = function () .....
但这也不起作用。另一个 SO question 建议像我现在一样格式化它,但它仍然无法识别它。