我是JavaScript的新手,我正在运行一个非常基本的代码但是遇到了麻烦。代码如下
MyService.js
var http = require('http');
var express = require('express');
var app = express();
var gpioControl = require('./GPIOController');
app.get('/pressUp/', function (req, res){
console.log("Pressed Up");
gpioControl.upButtonPress();
});
app.get('/pressDown/', function (req, res){
console.log("Pressed Down");
gpioControl.downButtonPress();
});
app.listen(3000);
console.log("The server is running on port 3000");
GPIOController.js
var upButtonPress = function ()
{
console.log ("UP Button has been pressed!");
}
var downButtonPress = function()
{
console.log ("Down Button has been pressed!");
}
我得到的错误如下:
TypeError: undefined is not a function
at C:\Users\mehroz\Desktop\Rasberry Pi Automation\MyService.js:11:14
at Layer.handle [as handle_request] (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\layer.js:82:5)
at next (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\route.js:110:13)
at Route.dispatch (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\route.js:91:3)
at Layer.handle [as handle_request] (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\layer.js:82:5)
at C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\index.js:267:22
at Function.proto.process_params (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\index.js:321:12)
at next (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\index.js:261:10)
at expressInit (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\middleware\init.js:23:5)
at Layer.handle [as handle_request] (C:\Users\mehroz\Desktop\Rasberry Pi Automation\node_modules\express\lib\router\layer.js:82:5)
答案 0 :(得分:1)
如果GPIOController.js是一个节点模块(它看起来像是),它需要使用CommonJS模式。话虽这么说,您应该将GPIOController中的var声明更改为导出。 your-function-name-here 声明。
因此,var upButtonPress = function(){}将成为
exports.upButtonPress = function(){}
然后,当您在MyService.js中使用它时,它将起作用。