【问题标题】:Node.js Express PUT Functionality - Saving dataNode.js Express PUT 功能 - 保存数据
【发布时间】:2014-03-18 19:28:28
【问题描述】:

我第一次使用 Node 和 Express 设置服务器,但无法保存我在 PUT 调用中检索到的响应。这是一项调查 - 我需要使用在调查中输入的“响应”对象更新模型。

我确实在控制台中看到了正确的响应输出,但从我的“保存”功能。

提前谢谢你。

kitty-questions.json

[
{
    "id": "favorite-food",
    "number": "1",
    "url": "favorite-food",
    "name": "Favorite Food",
    "question": "Which of the following best describes your kitty's palatte?",
    "responded" : "default response",
    "query": "Which of the following best describes your kitty's palatte?",
    "answers": {
        "Grumpy" : "Fresh Water Salmon, no bones, served on china",
        "Hipster" : "Nothing - trying to fit into newer, tighter jeans",
        "Pudge" : "Anything and everything my owner is eating",
        "Bub" : "Mice",
        "Meow" : "Roaches"
    }
},
{
    "id": "favorite-band",
    "number": "2",
    "url": "favorite-band",
    "name": "Favorite Band",
    "question": "Your kitty claws at you desperatly when it wants to listen to:",
    "responded" : "default response",
    "query": "Which of the following best describes your kitty's palatte?",
    "answers": {
        "Bub" : "Country",
        "Grumpy" : "Mozart. Popular music is for the plebs.",
        "Pudge" : "z100",
        "Meow" : "Very heavy metal",
        "Hipster" : "something long winded"
    }
}

Server.js

var express = require('express'),
   http = require('http'),
   questions = require('./data/kitty-questions');

 var app = express()
  .use(express.bodyParser())
  .use(express.static('public'));

  app.get('/questions', function  (req, res) {
    res.json(questions);
  });

  app.post('/questions', function  (req, res) {
       var matches = questions.filter(function  (question) {
       return question.url === req.body.url;
    });

       if (matches.length > 0) {
          res.json(409, {status: 'question already exists'});
        } else {
           req.body.id = req.body.url;
           questions.push(req.body);
           res.json(req.body);
       }
   });

   app.put('/questions/:question_name', function (req, res) {
       var matches = questions.filter(function  (question) {
         return question.url === req.params.question_name;
   }); 

    var catResponse = req.body.responded;
     console.log(JSON.stringify(catResponse));

    return questions.findById(req.params.question_name, function (err, question) {
        question.catResponse = req.body.responded;
        return question.save(function (err) {
           if (!err) {
           console.log("updated");
           } else {
           console.log(err);
           }
       return res.send(question);
      });
   });    

  });

app.get('/questions/:question_name', function  (req, res) {
  var matches = questions.filter(function  (question) {
    return question.url === req.params.question_name;
});

  if (matches.length > 0) {
     res.json(matches[0]);
   } else {
    res.json(404, {status: 'invalid survey question'});
   }

 });

app.delete('/questions/:question_name', function  (req, res) {
  var found = false;
  items.forEach(function (question, index) {
      if (question.url === req.params.question_name) {
         found = index;
      }
   });

   if (found) {
      items.splice(found, 1);
      res.json(200, {status: 'deleted'});
    } else {
      res.json(404, {status: 'invalid survey question deletion'});
    }

   });


   app.get('/*', function  (req, res) {
     res.json(404, {status: 'not found'});
   });

  http.createServer(app).listen(3000, function () {
    console.log("Server ready at http://localhost:3000");
});

STRING FROM THE TERMINAL AFTER MAKING PUT CALL:

Server ready at http://localhost:3000

TypeError: Object [{"id":"favorite-food","number":"1","url":"favorite-food","name":"Favorite Food","question":"以下哪项最能描述您的猫咪的味觉?","re​​sponded":"默认响应","query":"以下哪项最能描述您的猫咪的味觉?","answers":{"Grumpy":"Fresh Water三文鱼,没有骨头,盛在瓷器上","Hipster":"什么都没有 - 试图穿上更新、更紧的牛仔裤","Pudge":"我的主人正在吃的任何东西","Bub":"老鼠"," Meow":"Roaches"}},{"id":"favorite-band","number":"2","url":"favorite-band","name":"Favorite Band","question" :"当你的猫咪想听的时候,它会拼命地抓着你:","re​​sponded":"default response","query":"以下哪项最能描述你猫咪的味觉?","answers":{"Bub ":"Country","Grumpy":"莫扎特。流行音乐是为平民准备的。","Pudge":"z100","Meow":"Very heavy metal","Hipster":"something long-winded"} },{"id":"favorite-hideout","number":"3","url":"favorite-hideout","name":"Favorite Hideout","questio n":"你最有可能发现你的野兽栖息在这里:","re​​sponded":"","answers":{"Bub":"在你的肩膀上","Grumpy":"独自一人。任何地方,一个人。","Pudge":"在冰箱里","Meow":"放牧其他猫","Hipster":"外面,抽烟。"}},{"id":"favorite-friends" ,"number":"4","url":"favorite-friends","name":"Favorite Friends","question":"你的小猫一般相处融洽:","re​​sponded":""," answers":{"Bub":"其他猫","Grumpy":"没有人。","Pudge":"人类,动物,任何人。","Meow":"听话的动物","Hipster":" dog"}},{"id":"favorite-celebrity","number":"5","url":"favorite-celebrity","name":"Favorite Celebrity","question":"你的猫无法获得足够的这个红地毯步行者:","re​​sponded":"","answers":{"Bub":"Meg Ryan","Grumpy":"Jack Nicholson","Pudge":"John Candy", "Meow":"麦克阿瑟将军算吗?","Hipster":"Zooey Deschanel"}}] 没有方法 'update'

3/19 UPDATE:

 app.put('/questions/:question_name', function (req, res) {

      var question = questions.filter(function  (question) {
      return question.url === req.params.question_name;

   }); 

   var defaultResponse = question[0].responded;
   res.json(defaultResponse);

   var catResponse = req.body.responded;

    questions.update({id: req.params.question_name}, function (err, question) {
    question.catResponse = catResponse;

    question.save(function (err) {
       if (!err) {
           res.send(catResponse);
       } else {
          res.send(400); //or something
       }

     });
   });

 });    

【问题讨论】:

  • 节点代码会更有帮助
  • 它在那里 - 在 server.js 部分下
  • 哦,没看到滚动条,谢谢
  • 也许你想要整个 server.js 文件?
  • 刚刚更新为包含所有 server.js

标签: node.js backbone.js express put


【解决方案1】:

这里有很多不必要的返回,至少,它们使代码难以阅读。

删除一些东西并忽略匹配变量,因为 PUT 本身没有使用它,这样的东西可能更符合您的要求:

app.put('/questions/:question_name', function (req, res) {

    var catResponse = req.body.responded;

    questions.update({id: req.params.question_name}, function (err, question) {
        question.catResponse = catResponse;

        question.save(function (err) {
           if (!err) {
               res.send(question);
           } else {
              res.send(400); //or something
           }

      });
   });    

});

*编辑*

我假设 questions = require('./data/kitty-questions');是你的猫鼬模型。您需要问题才能成为猫鼬模型才能进行更新。

喜欢:

var mongoose = require('mongoose')
, Questions = mongoose.model('Question')

那么您的问题模型文件可能如下所示:

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;
var ObjectId = Schema.ObjectId;

QuestionSchema = new Schema({
    //keys and stuff in here

});

mongoose.model('Question', QuestionSchema);

【讨论】:

  • 谢谢 - 这更干净。当我使用此新代码发出 PUT 请求时,出现以下错误:
  • TypeError: Object [object Object],[object Object],[object Object],[object Object],[object Object] 没有方法'update'
  • 你能把你发的东西贴在put里面吗?字符串化它
  • 我刚刚在原始帖子的底部添加了我要更新的字符串。
  • 您实际上向服务器发送了什么?它应该只是类似于 Request: PUT localhost:80/questions/favorite-food body: {responded: "default response"} 就这样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多