node.js 要求未以角度定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26012018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:54:41  来源:igfitidea点击:

require is not defined in angular

node.jsangularjs

提问by kawade

I am using angularjs where i have created a js file(loginCtrl.js) and i have inclused a controller. I have defined my db connection and schema in another file(server.js) and i want to include that file in my js.

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

My loginCtrl.js looks like:

我的 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);
   }

});

and my server.js files looks like:

我的 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');

When i run the code, it gives the error like:

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

ReferenceError: require is not defined

It is printing the console.log defined above.

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

回答by ploutch

require()is a NodeJS function, your angular controller will be executed in the browser, which doesn't have that built-in function. If you want to replicate that behavior client-side, you should look at RequireJS

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