How to post data to mongo collection using Mean stack?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 15:06:51

问题


I have a object that contains firstname and lastname from client it is printing in client factory so i am new to backend development so i created user schema and api to post the data but it is throwing 404 error . Error mentioned below in question. Any idea what is implemented wrong ?

clientFactory.js

 create : function(userData) {
            console.log('factory',userData);
            return $http.post('/api/users', userData);

        }

Server code

app > routes.js

  module.exports = function(app) {

      app.use('api/users', require('./api/user'));
      app.get('*', function(req, res) {
          res.sendfile('./public/views/index.html'); // load our public/index.html file
          // res.sendFile(path.join(__dirname, ''../public/views/index.html'')); 
      });

  };

Folders under app > api > user

user.index.js

var express = require('express');
var controller = require('./user.controller');

var router = express.Router();

router.get('/', controller.index);
router.post('/',controller.create);

module.exports = router;

user.model.js

var mongoose = require('bluebird').promisifyAll(require('mongoose'));

var UserSchema = new mongoose.Schema({
  firstName: String,
  lastName: String
});

module.exports = mongoose.model('User', UserSchema);

user.controller.js

exports.create = function(req, res) {
  console.log(req.body);
  User.createAsync(req.body)
    .then(responseWithResult(res, 201))
    .catch(handleError(res));
}

Error

angular.js:12410 POST http://localhost:8080/api/users 404 (Not Found)
(anonymous) @ angular.js:12410
p @ angular.js:12155
(anonymous) @ angular.js:11908
(anonymous) @ angular.js:16648
$eval @ angular.js:17972
$digest @ angular.js:17786
$apply @ angular.js:18080
(anonymous) @ angular.js:26749
cg @ angular.js:3613
d @ angular.js:3601
angular.js:14328 Possibly unhandled rejection: {"data":"Cannot POST /api/users\n","status":404,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/users","data":{"firstName":"Kun","lastName":"Zhang"},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"Not Found"}

回答1:


Angular error stack trace is very clear.
You do not handle this specific endpoint for your POST query in your express router.

So the server throw a 404 error, as it should.

Try something like this:

router
    .post('/api/users', function (req, res) {
       // do what you want with your user here
    })

With express (and NodeJS) you must explicitly specify each access to server resources.

As side note, you are pretty close to this but try to keep your application logic simple for maintenability.



来源:https://stackoverflow.com/questions/41644624/how-to-post-data-to-mongo-collection-using-mean-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!