Node.js在HTTP Rest Developement

时间:2015-12-29 16:13:46

标签: javascript node.js mongodb

我正在尝试建立一个MEAN项目。客户端已完成。但是从服务器端,我无法进行新的插入(使用HTTP Post完成)。

在这里,我向您展示了我如何使用索引(它是一个简单的MongoDB数据列表)。但首先,我将向您展示我的数据模型和数据库:

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

//My Schema
var Sch = mongoose.Schema(
    {
    titulo: String,
    descripcion: String,
    precio: Number,
    imagen: String} );

//Access to Prueba db 
var db = mongoose.createConnection('mongodb://localhost:27017/prueba');
//Stablish our model
Camis = db.model('camisetas',Sch);

//Make accesible for other modules
module.exports = Camis;

index.js:

var express = require('express');
var router = express.Router();
//model with connection
var Camis = require('./models');


//simply list the results

router.get('/', function(req, res, next) {

    var a = Camis.find().lean().exec(function(err, results){

    console.log('find DONE'+results.length);
    res.render('index', { camis: results } );

    });
});
//Real model-data work
var camisetas = require('./camisetas');
camisetas.setModel(Camis);
/*
::::::Verbs HTTP:::::
**
**get()-- Mostrar registros
**post()-- Insertar nuevos registros
**put()-- Modificar
**delete()-- Eliminar
*/

router.get('/camisetas', camisetas.index);

//I use it first to create the forms, not posting
router.get('/camisetas/create', camisetas.create);

//The real "post" that cames from create and then, stores the new "Camisetas" object
router.post('/camisetas', camisetas.store);
//Other routes that doesn't matter me
router.get('/camisetas/:id', camisetas.show);

router.get('/camisetas/:id/edit', camisetas.edit);

router.put('/camisetas/:id', camisetas.update);

router.delete('/camisetas/:id', camisetas.destroy);

module.exports = router;

正如大家所看到的,我已经评论了哪些方面有效,以及我如何发布POST的想法。

camisetas.js

var Camiseta;


exports.setModel = function(modelo){
   Camiseta = modelo;
};

//index
exports.index = function(req, res){

   Camis.find({}, function(error, result){
      if(error)
         res.send('[ERR] camisetas.js (index)');
      else
         res.render('camisetas/index', { camisetas: result });
    })
};

//create
exports.create = function(req, res){
   res.render('camisetas/save', {
      put: false,
      action: '/camisetas/',
      camiseta: new Camiseta({
         titulo: '',
         descripcion: '',
         precio: 0,
         imagen: ''
      })
   });
};
//save
exports.store = function(req, res){

   var camiseta = new Camiseta({
      titulo: req.body.camiseta.titulo,
      descripcion: req.body.camiseta.descripcion,
      precio: req.body.camiseta.precio,
      imagen: req.body.camiseta.imagen
   });

   camiseta.save(function(error, documento){
      if(error){
         res.send('Error al intentar guardar la camiseta.');
      }else{ 
         res.redirect('/camisetas');
      }
   });
};
exports.show = function(req, res){
   //
};
exports.edit = function(req, res){
   //
};
exports.update = function(req, res){
   //
};
exports.destroy = function(req, res){
   //
};

index.jade:

extends layout
block content
  h1 Camisetas
  p
    a(href="/camisetas/create") Crear nueva camiseta
  -if(camis.length > 0)
    table
      thead
        tr
          th Titulo
          th Descripcion
          th 
          th
          th
      tbody
        -each item in camis
          tr
            td #{item.titulo}
            td #{item.descripcion}
            td Ver
            td Editar
            td Eliminar
  -else
    p No existen Camisetas.

save.jade:

extends ../layout
block content
  h1 Guardar camiseta
  form(method="post", action="#{action}")
    -if(put)
      input(type="hidden", name="_method", value="PUT")
    label Titulo
    br
    input(type="text", name="titulo", required="required", value="#{camiseta.titulo}")
    br
    label Precio
    br
    input(type="text", name="precio", required="required", value="#{camiseta.precio}")
    br
    label Imagen
    br
    input(type="text", name="imagen", required="required", value="#{camiseta.imagen}")
    br
    label Descripcion
    br
    textarea(name="descripcion", cols="50", rows="5", required="required") #{camiseta.descripcion}
    br
    input(type="submit", value="Guardar")
    a(href="/personajes") Cancelar

最后,Chrome的输出,在我尝试创建并发布它的情况下(我正确输入表单,当我尝试POST它时会抛出错误):

Cannot read property 'camiseta' of undefined

TypeError: Cannot read property 'camiseta' of undefined
    at exports.store (C:\Users\reinoso\Desktop\server\myapp\routes\camisetas.js:36:23)
    at Layer.handle [as handle_request] (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\route.js:131:13)
    at Route.dispatch (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\index.js:277:22
    at Function.process_params (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\index.js:330:12)
    at next (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\index.js:271:10)
    at Function.handle (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\index.js:176:3)
    at router (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\index.js:46:12)
    at Layer.handle [as handle_request] (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\index.js:312:13)
    at C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\index.js:280:7
    at Function.process_params (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\index.js:330:12)
    at next (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\router\index.js:271:10)
    at expressInit (C:\Users\reinoso\Desktop\server\myapp\node_modules\express\lib\middleware\init.js:33:5)

1 个答案:

答案 0 :(得分:0)

您要么错过正在解析中间件的正文(例如http://example.com/mysound.wav和/或body-parser),要么该请求没有正文(例如,它不是multipart/form-dataapplication/x-www-form-urlencodedDevice请求。)