W
W
whiteleaf2017-10-07 22:55:31
Angular
whiteleaf, 2017-10-07 22:55:31

How to send post requests?

Please tell me how to correctly send post requests and correctly write to the mongoDB database.
Am I doing something wrong here:
browser error

zone.js:2933 POST http://localhost:3000/tasks 500 (Internal Server Error)
scheduleTask @ zone.js:2933
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:411
onScheduleTask @ zone.js:301
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:405
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:236
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.scheduleMacroTask @ zone.js:259
(anonymous) @ zone.js:2966
proto.(anonymous function) @ zone.js:1366
(anonymous) @ http.es5.js:1275
webpackJsonp.../../../../rxjs/Observable.js.Observable._trySubscribe @ Observable.js:171
webpackJsonp.../../../../rxjs/Observable.js.Observable.subscribe @ Observable.js:159
webpackJsonp.../../../../rxjs/operator/map.js.MapOperator.call @ map.js:54
webpackJsonp.../../../../rxjs/Observable.js.Observable.subscribe @ Observable.js:156
webpackJsonp.../../../../../src/app/tasks/tasks.component.ts.TasksComponent.addTask @ tasks.component.ts:34
(anonymous) @ TasksComponent.html:1
handleEvent @ core.es5.js:12023
callWithDebugContext @ core.es5.js:13493
debugHandleEvent @ core.es5.js:13081
dispatchEvent @ core.es5.js:8615
(anonymous) @ core.es5.js:9226
(anonymous) @ platform-browser.es5.js:2651
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:425
onInvokeTask @ core.es5.js:3881
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:424
webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask @ zone.js:192
webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:499
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
core.es5.js:1020 ERROR Response {_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta char…rve-static\index.js:75:16)</pre>↵</body>↵</html>↵", status: 500, ok: false, statusText: "Internal Server Error", headers: Headers, …}

console error
TypeError: Tasks.save is not a function
tasks.js
const express = require('express');
const router = express.Router();

// Mongoose
var Task = require('../models/tasks');

/* GET all tasks */
router.get('/', (req, res) => {

  Task.find({}).exec(function(err, data) {
    if(err) console.error(err);
    res.json(data);
  });
});

/* GET One Task */
router.get('/:id', (req, res) => {
  var id = req.params.id;

  Task.findOne({_id: id}).exec(function(err, data) {
    if(err) console.error(err);
    res.json(data);
  });
});

/* Save Task */
router.post('/', (req, res) => {
  var task = req.body;

  console.log('task.api');


  if(!task.title || !(task.isDone + '')){
    res.status(400);
    res.json({
      'error': 'Bad data'
    });
  } else {
    Task.save(task, function(err, task){
      if(err){
        res.send(err);
      }
      res.json(task);
    });
  }
});

/* Delete One Task */
router.delete('/:id', (req, res) => {
  var id = req.params.id;

  Task.findOne({_id: id}).exec(function(err, data) {
    if(err) console.error(err);
    res.json(data);
  });
});

/* Update One Task */
router.put('/:id', (req, res) => {
  var task = req.body;
  var updTask = {};

  if(task.isDone){
    updTask.isDone = task.isDone;
  }

  if(task.title){
    updTask.title = task.title;
  }

  if(!updTask){
    res.status(400);
    res.json({'error':'Bad Data'});
  } else {
    Task.update({_id: req.params.id}, updTask, {}).exec(function(err, data) {
      if(err) console.error(err);
      res.json(data);
    });
  }
});
module.exports = router;

task.service.ts
import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class TaskService {

  constructor(private http: Http) {
    console.log('Task Service is initialized...');
  }

  getAllTasks(){
    return this.http.get('/tasks')
      .map(res => res.json());
  }

  addTask(task){

    console.log('task.service');

    var headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
    var options = new RequestOptions({ headers: headers }); // Create a request option
    //var headers = new Headers();
    //headers.append('Content-Type', 'application/json');
    return this.http.post('/tasks',JSON.stringify(task),options)
      .map(res => res.json());
  }
}

tasks.js
// grab the things we need
var mongoose = require('../MongooseConnect');
var Schema = mongoose.Schema;

// create a schema
var TaskSchema = new Schema({
  title: { type: String, required: true },
  isDone: { type: String, required: true },
  created_at: Date,
  updated_at: Date
});

// the schema is useless so far
// we need to create a model using it
var Task = mongoose.model('Task', TaskSchema);

// make this available to our users in our Node applications
module.exports = Task;

mongooseConnect
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var options = {
  useMongoClient: true
};
mongoose.connect('mongodb://localhost:27017/tasks', options);
module.exports = mongoose;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wondergrauf, 2017-11-01
@Wondergrauf

In tasks.services.ts change these lines:

return this.http.post('/tasks',JSON.stringify(task),options)
  .map(res => res.json());

For something like this:
return this.http.post('/tasks', task, options)
  .map(res => res.json());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question