gpt4 book ai didi

javascript - 从 Angular2 组件传递 Json 到 Node.js

转载 作者:行者123 更新时间:2023-11-30 15:41:45 25 4
gpt4 key购买 nike

我正在尝试从 Angular2 和 Node.js 将数据插入数据库

当我运行我的脚本时,我 console.log(this.address);确保我通过 json这是控制台的输出。

Address {street: "1111 NW 40TH AVE", city: "MIAMI", state: "Florida", zip: "33167"}

但是记录没有进入数据库。我知道我有一个连接但我在这里遗漏了一些东西并且不确定如何从这里解决它。

在组件中这是 http.post

 addressSubmit() { 
this.addressSubmitted = true;
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http
.post('http://localhost:4200/profile/addAddress', this.address, { headers: headers })
.map(response => response.json());
console.log(this.address);
}

因此,通过该函数,我知道我有一个似乎正在传递 json 的函数.

然后在带有 Node 的后端,我收到这样的 json,

addAddress: function(req, res) {
pool.connect(function(err, client, done) {
if (err) {
return console.error('error fetching client from pool', err);
} // end of error catch while creating pool connection

var query = client.query("insert into address (street, city, state, zip) " +
"values ('" + req.query.street + "','" + req.query.city + "','" +
req.query.state + "','" + req.query.zip + "')"); // create the query

query.on("end", function(result) {
client.end();
res.write('Success');
res.end();
}); // handle the query
done(); // release the client back to the pool
}); // end of pool connection
pool.on('error', function(err, client) {
console.error('idle client error', err.message, err.stack)
}); // handle any error with the pool
} // End addAddress function

像这样处理路由,

router.get('/profile/addAddress', connection.addAddress);

在 app.js 中

app.get('/profile/addAddress', function(req,res){
db.addAddress(req,res);
});

所以在这一点上。我知道我正在传递 json。我知道我与数据库有连接。我可以通过手动输入条目并转到 express route 来检索条目并将它们输出到浏览器。 .

我只是缺少从 angular2 来回传递数据至 node .然后从node返回angular2 .

现在在 echonax 答案的帮助下,我在“网络”选项卡下的查询字符串中有了这个,

查询字符串参数

street:11700 NW 36TH AVE
city:MIAMI
state:Florida
zip:33167

最佳答案

我认为您没有向后端发出请求。

你的

this.http
.post('http://localhost:4200/profile/addAddress', this.address, { headers: headers })
.map(response => response.json());

line 返回一个 Observable,这个 observable 仅在订阅时被调用。

所以让你的 addressSubmit() 像这样返回这个 observable:

 addressSubmit() { 
this.addressSubmitted = true;
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post('http://localhost:4200/profile/addAddress', this.address, { headers: headers })
.map(response => response.json());
}

然后在你的代码中这样调用它:

this.addressSubmit().subscribe((response)=>{
//do something with the response here
console.log(response);
})

关于javascript - 从 Angular2 组件传递 Json 到 Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40698058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com