所以我想发送一些 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/