【发布时间】:2017-04-03 13:01:44
【问题描述】:
我正在尝试从 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 的函数。
然后在带有节点的后端我收到这样的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
【问题讨论】:
-
你怎么打电话给
addressSubmit()? -
能否在开发者控制台中查看网络请求。如果您使用 chrome,您可以通过打开开发工具然后单击网络来执行此操作。单击触发发布请求的按钮。检查您的开发工具以查看调用是否已触发并且它具有正确的正文和参数。然后检查响应。您期望该函数对响应数据做什么?您将响应映射到 json,但不从函数返回 json 数组。你怎么知道它不起作用?
-
我正在尝试将数据插入数据库。所以在我提交表单后,我正在检查控制台,我看到那里输出了 json。然后我检查数据库并没有创建新条目。至于 addressSubmit 被称为是,这是运行 console.log(this.address); 的函数当我检查“网络”选项卡然后单击“标题”时,json 不在其中。
标签: javascript json node.js angular