mysql - 从 Angular2 组件向 node.js 发送数据

标签 mysql node.js angular express

所以我想发送一些 string 值到我的 Node 服务器并在 MySQL 表中找到该值。

我有一个从服务获取数据的组件

ngOnInit() {
    this.instructionsService.getAllInstructions().subscribe(instructions => {
      this.instructions = instructions;
    });
}

然后我有一个从 Node 服务器获取数据的服务

getAllInstructions() {
    return this.http.get('/api/profile/')
      .map(res => res.json());
}

最后我有了 Node api

app.get('/profile',getAllInstructions);
function getAllInstructions(req,res){
connection.query("select * from users where id='somekindofid'",function(err, rows, fields) {
        res.json(rows);
    }
}

`

我想用我的组件发送的值替换那个'somekindofid'

我该怎么做?

最佳答案

您应该将 id 传递给其 URL 本身内的 Node 方法。 同样,您应该将 API 路由更改为 /profile/:id,其中 id 是将从 API 使用者传递的参数。

Node

app.get('/profile/:id',getAllInstructions);
function getAllInstructions(req,res){
   connection.query("select * from users where id="+ req.params.id,function(err, rows, fields) {
        res.json(rows);
    }
}

服务

getAllInstructions(id) {
    return this.http.get(`/api/profile/${id}`)
      .map(res => res.json());
}

组件

ngOnInit() {
    let userId = 'pankaj';
    this.instructionsService.getAllInstructions(userId).subscribe(instructions => {
      this.instructions = instructions;
    });
}

关于mysql - 从 Angular2 组件向 node.js 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42716465/

相关文章:

json - 我的 Node.js hubot 代码中出现奇怪的 JSON.parse 错误

node.js - Kraken.js:使用 Jade 作为模板?

node.js - 当设置为生产模式 : No formatters or parsers provided 时,Webpack Globalize 构建失败

Mysql 在一次查询中选择 group by 和不使用 group by

php - 如何在php中动态链接页面到菜单?

php - 如果表单字段输入为空而不是在数据库 CodeIgniter 中更新

javascript - Angular:如何在输入字段中强制大写

MySQL连接问题

angular - IntelliJ 理念 : custom imports path

angularjs - 深入检查类似于 Angular2 中 $watchCollection 的变化