Javascript 未定义的var module.exports
由于某些原因,我无法从单独的自定义模块中获取module.exports函数返回的值。我从超过10篇研究文章的许多来源尝试了许多方法。如果你想投反对票,请阅读我的简历,或者如果你想帮忙,我会很乐意接受你的回答 //restapi/index.jsJavascript 未定义的var module.exports,javascript,node.js,undefined,Javascript,Node.js,Undefined,由于某些原因,我无法从单独的自定义模块中获取module.exports函数返回的值。我从超过10篇研究文章的许多来源尝试了许多方法。如果你想投反对票,请阅读我的简历,或者如果你想帮忙,我会很乐意接受你的回答 //restapi/index.js module.exports = function gifs() { giphy.search('Pokemon', function (err, res) { return res.data[0]; }); } /
module.exports = function gifs() {
giphy.search('Pokemon', function (err, res) {
return res.data[0];
});
}
// main server.js
var readapi = require('restapi')
console.log(readapi.gifs());
// Output:__________________
TypeError: readapi.gifs is not a function
试试这个代码
module.exports.gifs = function gifs() {
return new Promise((resolve, reject) => {
giphy.search('Pokemon', function (err, res) {
if (err) reject(err);
else resolve(res.data[0]);
});
});
}
// main server.js
var readapi = require('restapi')
readapi.gifs().then(console.log);
试试这个代码
module.exports.gifs = function gifs() {
return new Promise((resolve, reject) => {
giphy.search('Pokemon', function (err, res) {
if (err) reject(err);
else resolve(res.data[0]);
});
});
}
// main server.js
var readapi = require('restapi')
readapi.gifs().then(console.log);
您正在导出一个函数,而不是一个带有函数的对象,并且正在将同步函数(
console.log
)与异步操作一起使用。。这行不通
你需要这样写:
module.exports=函数gifs(cb){
搜索('Pokemon',函数(err,res){
if(err){cb(err)}
else{cb(null,res.data[0])}
});
}
----
var readapi=require('restapi')
readapi((err,data)=>{console.log({err,data})})
记住以下两者之间的区别:
module.export = {
hello: () => { console.log('world') }
}
// usage: require('./hello').hello()
module.export = () => { console.log('world') }
// usage: require('./hello')()
您正在导出一个函数,而不是一个带有函数的对象,并且正在将同步函数(
console.log
)与异步操作一起使用。。这行不通
你需要这样写:
module.exports=函数gifs(cb){
搜索('Pokemon',函数(err,res){
if(err){cb(err)}
else{cb(null,res.data[0])}
});
}
----
var readapi=require('restapi')
readapi((err,data)=>{console.log({err,data})})
记住以下两者之间的区别:
module.export = {
hello: () => { console.log('world') }
}
// usage: require('./hello').hello()
module.export = () => { console.log('world') }
// usage: require('./hello')()
如何将参数传递到readapi()函数中?如果我尝试传递一个字符串,我会得到意外的字符串。
readapi
是函数本身,因此您只需传递参数readapi('arg1','arg2',cb)
,并且在实现函数时module.exports=函数gifs(arg1,arg2,cb){..
谢谢。我不认为我可以在结束括号后添加参数。如何将参数传递到readapi()函数?如果我尝试传递一个参数,会得到意外的字符串。readapi
是函数本身,因此您只需传递参数readapi('arg1','arg2',cb)
当您实现函数时module.exports=函数gifs(arg1,arg2,cb){..
谢谢。我想我不能在结束括号后添加