将Json从Angular2组件传递给Node.js

我试图从Angular2和Node.js插入数据到数据库

当我运行我的脚本我console.log(this.address); 以确保我传递json ,这是输出到控制台。

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

但logging没有进入数据库。 我知道我有一个连接,但我在这里失去了一些东西,不知道如何麻烦从这里拍摄它。

在组件这是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); } 

所以有了这个function,我知道我有一个function,似乎是传递json

然后在节点的后端,我正在接收这样的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。 我知道我有一个连接到数据库。 我可以通过手动input和express route来检索条目并将其输出到浏览器。

我只是错过了从angular2node来回传递数据。 然后从node回到angular2

现在在echonax答案的帮助下,我在networking选项卡下的查询string中,

查询string参数

 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()返回这样的可观察性:

  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); })