简体   繁体   English

TypeError:undefined不是Node JS函数

[英]TypeError: undefined is not a function Node JS

I am newbie to JavaScript, I am running a very basic code but having trouble with it. 我是JavaScript的新手,我正在运行一个非常基本的代码,但是遇到了麻烦。 The code is as follows 代码如下

MyService.js 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 GPIOController.js

var upButtonPress = function ()
{
    console.log ("UP Button has been pressed!");
}

var downButtonPress = function()
{
    console.log ("Down Button has been pressed!");
}

The Error I get is below : 我得到的错误如下:

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) 

if GPIOController.js is a node module (which it looks like it is), it needs to use the CommonJS pattern. 如果GPIOController.js是一个节点模块(看起来像它),则需要使用CommonJS模式。 That being said, you should change the var declarations in GPIOController to be exports. 话虽如此,您应该将GPIOController中的var声明更改为export。 your-function-name-here declarations. 您的功能名称在这里声明。

So, var upButtonPress = function(){} would become 因此,var upButtonPress = function(){}将变为

exports.upButtonPress = function(){}

It would then work as you are using it in MyService.js. 然后,它将在您在MyService.js中使用时正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM