【问题标题】:MEAN Stack: post method is not reflecting in databaseMEAN Stack:post 方法未反映在数据库中
【发布时间】:2018-06-21 16:56:44
【问题描述】:

我正在尝试通过 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');

【问题讨论】:

  • 你在用mongo吗?在你的 jobList 模型中尝试设置 var mongoose = require('mongoose'); mongoose.set('debug', true);看看你是否在控制台中得到任何东西。
  • 发送this.http.post('http://localhost:3000/api/appliedjobs', selected,{headers})之前不要字符串化
  • 是的,我试过没用...

标签: javascript angular typescript http mean-stack


【解决方案1】:

您不需要像 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 是一个 observable,需要订阅才能进行 http 调用:

addJobList(theJobItem).subscribe(data => console.log(data));

【讨论】:

    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多