简体   繁体   English

如何使用express.js,mongoose和jade创建帖子请求

[英]How to create posts requests with express.js , mongoose and jade

The below code is from a tutorial I'm doing. 下面的代码来自我正在做的教程。 I want to know how to capture and respond to post requests. 我想知道如何捕获并响应帖子的请求。 I thought this would be easy to understand but the problem is as follows. 我认为这很容易理解,但是问题如下。

First here is the code: 首先是代码:

Node 节点

app.post('/tasks', function(req, res){
  var task = new Task(req.body.task);   // This line 
  task.save(function (err) {
    if (!err) {
      res.redirect('/tasks/new');
    }
    else {
      throw err;
    }
  });
});

Jade

extends ../layout

block content
  h1 New task view

  form(role='form', method='post', action='/tasks')
    fieldset
      legend Add a task
      div.form-group
        label Task
        input(name='task[task]', class='form-control')  // This line
      button.btn.btn-primary(type='submit') Submit
      button.btn.btn-default(type='reset') Clear

Mongoose 猫鼬

mongoose.connect('mongodb://localhost/todo_development');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var Task = new Schema({
  task: { type: String, required: true }
});

var Task = mongoose.model('Task', Task);

In the first two blocks of code above each has a comment called 'this line'. 在上面的前两个代码块中,每个代码块都有一个称为“此行”的注释。 Within these lines are the word task as attributes/properties. 这些行中的任务一词是属性/属性。 When I change these to something else like 'oink' it breaks the code. 当我将其更改为其他类似“ oink”的代码时,它将破坏代码。

So for example if I do: 例如,如果我这样做:

node 节点

  var task = new Task(req.body.oink);   // This line 

jade

input(name='oink[oink]', class='form-control')  // This line

It no worky. 没用。 I am not sure why nor how to do posts requests correctly. 我不确定为什么也不能正确地发布请求。 :( :(

Try changing this line 尝试更改此行

var task = new Task(req.body.task);

To this: 对此:

var task = new Task(req.body);

I'm not very familiar with Jade, but as far as I can tell from Submit Jade form you should name your input like... 我对Jade不太熟悉,但是据我可以从Submit Jade表单中得知,您应该将输入命名为...

input(id='password',type='password',value='',placeholder='',name='password')

Also, what does your mongoose schema look like? 另外,您的猫鼬模式是什么样的? That may be helpful. 这可能会有所帮助。

You have defined the variable "Task" twice. 您已经两次定义了变量“任务”。 Try this... 尝试这个...

var taskSchema = new Schema({
  task: { type: String, required: true }
});

var Task = mongoose.model('Task', taskSchema);

put: input(name='task[]', class='form-control') // This line put:input(name ='task []',class ='form-control')//此行

and put this: var task = new Task({'task':req.body.task}); 并输入:var task = new Task({'task':req.body.task}); // This line //这行

luck 运气

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM