我想将 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 install 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);
}
});
如果我在 Component 的构造函数中使用此连接代码,则会返回一些错误,例如
ERROR in ./~/mysql/lib/Connection.js
Module not found: Error: Can't resolve 'net'
那么如何将连接代码与 http.get() 请求集成?
非常感谢。
添加:现在我来到这里(它涉及我的 Angular Universal 入门项目 https://github.com/angular/universal-starter):
在 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 为目标进行打包时,webpack 提供了一个自定义 Node 环境的选项。 The default configuration is:
node: {
console: false,
global: true,
process: true,
Buffer: true,
__filename: "mock",
__dirname: "mock",
setImmediate: true
}
正如您所注意到的,webpack 的默认 Node 环境配置并未考虑诸如“net”之类的库。在服务器 webpack 配置 (针对 Node ) 中将网络库添加到 Node 环境属性应该会有所帮助(可能是 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
意味着不需要浏览器版本或模拟“net”,你需要模块本身,因为包在 Node 中运行。
关于node.js - 如何在 Angular Universal 中使用 HTTP Node.js 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42445647/