Thursday, 8 June 2017

(Angular2/NodeJS) POSTing to Mongolab doesn't insert into database

I'm working on my first solo MEAN stack project and have run into an early snag. I registered at mlab.com for an online database, created a collection called "Users" and have been able to successfully GET the users from this collection.

It also seems like I am able to successfully POST to that collection when I look at the response, but the data never actually gets added to the collection.

Here is my server.js file:

// Declarations
const express = require('express');
const bodyParser= require('body-parser');
const app = express();
var router = express.Router();
require('dotenv').config({path: 'keys.env'})

// Config
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

const MongoClient = require('mongodb').MongoClient;
var mongoLink = "mongodb://";
mongoLink += process.env.DB_USERNAME;
mongoLink += ':';
mongoLink += process.env.DB_PASSWORD;
mongoLink += '@ds113282.mlab.com:13282/turntup';
MongoClient.connect(mongoLink, (err, database) => {
  if (err) return console.log(err)
  db = database
  app.listen(8080, () => {
    console.log('Listening on 8080');
  })
});

// Routes
function handleError(res, reason, message, code) {
  console.log("ERROR: " + reason);
  res.status(code || 500).json({"error": message});
}

app.post("/api/users", function(req, res) {
  var newUser = req.body;

  if (!(req.body.firstName || req.body.lastName)) {
    handleError(res, "Invalid user input", "Must provide a first or last name.", 400);
  }
  console.log('NEW USER', newUser);
  db.collection('users').insertOne(newUser, function(err, doc) {
    console.log(doc);
    if (err) {
      handleError(res, err.message, "Failed to create new user.");
    } else {
      res.status(201).json(doc.ops[0]);
    }
  });
});

app.get('/api/users', (req, res) => {
  db.collection('Users').find().toArray(function(err, results) {
    res.send(results);
  })
});

And here is the relevant Angular 2 component:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

/*
  Generated class for the UserProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class UserProvider {
  url = 'http://localhost:8080/api/';
  constructor(public http: Http) {
    console.log('Hello UserProvider Provider');
  }

  createUser(data) {
    console.log(data);
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.http.post(this.url + 'users',
                           data,
                           {headers:headers})
    .map((res: Response) => res.json())
    .subscribe((res: Response) => {console.log(res)});
  }

  getUsers() {
    console.log('Getting users');
    return this.http.get(this.url + 'users')
      .map(res => res.json())
  }

}

The response that I get back from the POST endpoint returns an object with the firstName, lastName, and email attributes that I entered as well as the _id attribute that is used in Mongolab so it appears to be working.

I don't get any errors but the data is just not added to the Mongolab collection.

Where have I gone wrong?



via ClaytonAlanKinder

No comments:

Post a Comment