我正在尝试通过HTTP post方法传递一些数据,但是它没有反映在数据库中。 这是代码。
addJobList(jobitem) {
let headers = new Headers();
headers.append('Content-Type','application/json');
var selected = {
companyTitle : jobitem.company,
jobTitle : jobitem.jobtitle,
location : jobitem.location
}
console.log(selected);
this.http.post('http://localhost:3000/api/appliedjobs', JSON.stringify(selected),{headers: headers})
.map(res => res.json());
}
//getting jobs form back-end
getAppliedjobList() {
if (this.jobslist) {
return Promise.resolve(this.jobslist);
}
return new Promise( resolve => {
let headers = new Headers();
headers.append('Content-Type','application/json');
this.http.get('http://localhost:3000/api/appliedjobs',{headers: headers})
.map(res => res.json())
.subscribe(data => {
this.jobslist = data;
resolve(this.jobslist);
});
});
}
我已经在名为selected的对象中添加了数据。
{companyTitle: "Facebook", jobTitle: "System Engineer", location: "torinto,canada"}
控制台中的数据。但是此数据不会插入数据库中。 这是我的路线文件夹中的代码。
const jobList = require('../models/jobList');
router.post('/appliedjobs', function(req,res) {
console.log('posting');
jobList.create({
companyTitle: req.body.companyTitle,
jobTitle: req.body.jobTitle,
location: req.body.location
},function(err,list) {
if (err) {
console.log('err getting list '+ err);
} else {
res.json(list);
}
}
);
});
我没有收到任何错误,只是数据没有插入数据库中。 这是我的模特
var mongoose = require('mongoose');
const joblistSchema = mongoose.Schema({
companyTitle: String,
jobTitle: String,
location: String,
});
const JlSchema = module.exports = mongoose.model('JlSchema',joblistSchema,'joblist');
答案 0 :(得分:0)
您不需要像在example中那样对数据进行编码,而必须返回this.http.post。
addJobList(jobitem) {
let headers = new Headers();
headers.append('Content-Type','application/json');
const selected = {
companyTitle : jobitem.company,
jobTitle : jobitem.jobtitle,
location : jobitem.location
}
return this.http.post('http://localhost:3000/api/appliedjobs', selected, { headers: headers })
.map(res => res.json());
}
要使用它,您需要预订addJobList方法,http.post是可观察的,需要进行预订才能进行http调用:
addJobList(theJobItem).subscribe(data => console.log(data));