【问题标题】:require is not defined in angular要求没有在角度定义
【发布时间】:2014-11-18 15:48:20
【问题描述】:

我正在使用 angularjs,我在其中创建了一个 js 文件(loginCtrl.js),并且包含了一个控制器。 我已经在另一个文件(server.js)中定义了我的数据库连接和架构,我想将该文件包含在我的 js 中。

我的 loginCtrl.js 看起来像:

test.controller('loginCtrl', function($scope, loginService){

   $scope.login = function(user)
   {
       console.log('inside function 1');
       var user = require('./server.js')
      console.log('inside function');
       loginService.login(user);
   }

});

我的 server.js 文件看起来像:

var express = require('express');
var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/userregistration');

var userSchema = {
    username: String,
    firstname:String,
    lastname: String,
    email: String,
    password: String
}

var User = mongoose.model('User', userSchema, 'user');

当我运行代码时,它会给出如下错误:

ReferenceError: require is not defined

它正在打印上面定义的console.log。

【问题讨论】:

  • 你的 server.js 文件是由 NodeJs 运行的,而不是你的浏览器,对吧?
  • @meriadec:我如何确认这一点?
  • 如果您在终端中输入node server.js,您正在使用节点运行它,如果您在浏览器中包含server.js 脚本,您应该删除它:)
  • @meriadec:如何使它工作,以便我可以将其包含在我的 js 文件中...
  • 您永远无法在浏览器中连接 mongo。它是服务器端脚本。

标签: node.js angularjs


【解决方案1】:

require() 是一个 NodeJS 函数,你的 Angular 控制器将在没有该内置函数的浏览器中执行。如果您想在客户端复制该行为,您应该查看RequireJS

【讨论】:

  • 其实是commonjs/systemjs的一个函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 2015-11-03
  • 1970-01-01
  • 2018-08-20
  • 1970-01-01
  • 2015-03-17
相关资源
最近更新 更多