【问题标题】:How to use HTTP Node.js requests in Angular Universal如何在 Angular Universal 中使用 HTTP Node.js 请求
【发布时间】:2017-02-24 18:18:02
【问题描述】:

我想将 AngularJS 项目移至 Angular Universal。

在 AngularJS 中,我有使用 PHP 的 $http 请求。例如,我在服务中有以下代码:

this.getNewItems = function () {

    var request = $http({
        method: "GET",
        url: "PHP/newitems.php",
        params: {
            number: "3"
        }
    });

    return ( request.then(handleSuccess, handleError) );

};

现在我将 Node.js 与 Universal 一起使用,我想将 Http 请求与 Node.js 一起使用。

所以在组件的构造函数中我应该使用构造函数:

export class HomeComponent {
  mydata: any = {};

  constructor(http:Http) {

    http.get('??????').subscribe(data => {
      this.mydata = data;

    });
  }
}

如果我会使用 JSON 文件,那么我会发现很多这样的例子:

http.get('test.json').subscribe(data => {
    this.mydata = data;
});

但是我所有的数据都在现有的 MySQL 数据库中。所以我想了解如何访问数据库中的数据。

我已经通过

安装了 npm MySql 组件

npm 安装 mysql

我发现与 Node.js 的连接是通过以下方式设置的:

    var mysql = require('mysql');

    var connection = mysql.createConnection({
        host     : 'host',
        user     : 'user',
        password : 'password',
        database : 'dbname'
    });

    connection.connect(function(err) {
        // in case of error
        if(err){
            console.log(err.code);
            console.log(err.fatal);
        }
    });

如果我在组件的构造函数中使用此连接代码,则会返回一些错误,例如

ERROR in ./~/mysql/lib/Connection.js
Module not found: Error: Can't resolve 'net'

那么如何将连接代码与 http.get() 请求集成?

非常感谢。

补充:现在我来了(它涉及我的 Angular Universal https://github.com/angular/universal-starter 的入门项目):

  1. Component 我使用以下代码:

    导出类 HomeComponent {

        mydata:any = [];
    
        constructor(public model: ModelService) {
    
         this.model.get('/api/getmydata')
            .subscribe(data => {
    
              this.mydata = data;
              console.log("My data: " + this.mydata);
        });
        } 
    }
    

2.在 backend/api.ts 我添加了:

router.route('/getmydata')
      .get(function(req, res) {

        setTimeout(function() {
          res.json(Mydata);
        }, 0);
}

如果 Mydata 是 JSON,那么一切正常,我会收到数据。但是我想连接到 MySQL 数据库。所以我添加了一个连接代码:

router.route('/getmydata')
          .get(function(req, res) {

        var mysql = require('mysql');

        var connection = mysql.createConnection({
          host     : 'localhost',
          user     : 'root',
          password : 'root',
          database : 'mydatabase',
          port: '8889'
        });

        connection.connect(function(err) {
          if (err) {
            console.log("Error connecting to DB: " + err);
            throw err;
          }
        });
...

}

在这里我收到错误:

TypeError: Cannot read property 'on' of undefined
        at Protocol._enqueue (/Applications/MAMP/htdocs/Angular2/myproject/node_modules/mysql/lib/protocol/Protocol.js:152:5)
...

然后

Error connecting to DB: Error: Connection lost: The server closed the connection.

如果有人知道如何修复与数据库的连接,我将不胜感激。

【问题讨论】:

标签: node.js http get angular-universal


【解决方案1】:

以 node 为 target 打包时,webpack 提供了自定义 node 环境的选项。 The default configuration is:

node: {
  console: false,
  global: true,
  process: true,
  Buffer: true,
  __filename: "mock",
  __dirname: "mock",
  setImmediate: true
}

如您所见,webpack 的默认节点环境配置并未考虑诸如“net”之类的库。将 net 库添加到服务器 webpack 配置中的节点环境属性 (针对节点) 应该会有所帮助(可能是 webpack.config.js):

node: {
  // your existing props
  net: false
}

我选择将值设置为 false is trying to follow the code 的原因是解析这些属性。 The possible values are documented, but there's not enough documentation 关于自定义属性中每个值的含义。基本上(据我了解),false 意味着在浏览器版本或“网络”的模拟中不需要,您需要模块本身,因为包在节点中运行。

【讨论】:

    【解决方案2】:

    错误

    TypeError: Cannot read property 'on' of undefined ... 
    

    如果 Zone.js 的版本不正确或安装不正确,可能会发生这种情况。

    我发现我收到了警告:

    angular2-universal@2.1.0-rc.1 requires a peer of zone.js@~0.6.21 but none was installed. 
    

    所以安装Zone.js的命令是:

    npm install zone.js@0.6.21
    

    现在我成功地从 MySQL 数据库接收数据。

    完整代码为:

        router.route('/newvideos')
              .get(function(req, res) {
    
                var mysql = require('mysql');
    
                var connection = mysql.createConnection({
                  host     : 'localhost',
                  user     : 'root',
                  password : 'root',
                  database : 'myDB',
                  port: '8889'
                });
    
                connection.connect(function(err) {
                  if (err) {
                    console.log("Error connecting to DB: " + err);
                    throw err;
                  }
                });
    
                connection.query("SELECT * FROM table", function(err, rows, fields) {
                  if (err) {
                    console.log("Error executing query: " + err);
                    throw err;
                  }
    
                  connection.end();
    
                  setTimeout(function() {
                    res.json(rows);
                  }, 0);
             });
    
         })
    

    但是!!! 我发现在此之后使用 *ngFor 渲染的服务器停止工作!

    在 HTML 模板中我只见过:

     <!--template bindings={}-->
    

    我在简单的 JSON 返回时遇到了这个错误,没有连接到数据库。 所以我发现即使我返回 JSON 服务器渲染也会停止工作。 然后我安装了 Zone.js 没有版本:

    npm install zone.js
    

    又开始返回 JSON。在这种情况下,服务器渲染开始正常工作。 但是当我开始连接 MySQL 时,第一个原始错误就发生了。

    就我而言,现在我要么连接到 MySQL,要么连接到服务器渲染。不能同时两者兼而有之。

    如果有人知道如何解决此问题,我将不胜感激。谢谢。

    补充:我找到了解决办法。见Due to Zone.js in Angular Universal server rendering stops working. How to fix?

    【讨论】:

      猜你喜欢
      • 2017-11-27
      • 2017-02-22
      • 2017-08-02
      • 2013-02-08
      • 1970-01-01
      • 2021-06-12
      • 2020-01-29
      • 2017-12-20
      • 1970-01-01
      相关资源
      最近更新 更多