wrighti
wrighti

Reputation: 11

Express User is not defined

Hi I've been working through this tutorial and have run into a problem.

In my edit.jade file I have this -

form(method="POST", action="/users/")
    input(type="hidden", name="_method", value="PUT")
p Name:
    input#name(type="text", name="name", value="#{user.name}")
p Email:
    input#email(type="email", name="email", value="#{user.email}")
p Age:
    input#age(type="number", name="age", value="#{user.age}")
p: button(type="submit") Update

I call the view with this code -

app.param('name', function (req, res, next, name){
Users.find({ name: name }, function (err, docs) {
    req.user = docs[0];
    next();
});
});
app.get('/users/:name/edit', function (req, res){
res.render("users/edit", { user: req.user });
});

However, when rendering the edit.jade file, this error is thrown -

ReferenceError: edit.jade:6
4|      input(type="hidden", name="_method", value="PUT")
5|  p Name:
> 6|        input#name(type="text", name="name", value="#{user.name}")
7|  p Email:
8|      input#email(type="email", name="email", value="#{user.email}")
9|  p Age:

user is not defined
at eval (eval at <anonymous> (/usr/local/lib/node_modules/jade/lib/jade.js:171:8),<anonymous>:32:99)
at /usr/local/lib/node_modules/jade/lib/jade.js:172:35
at /usr/local/lib/node_modules/jade/bin/jade:154:17
at /usr/local/lib/node_modules/jade/node_modules/mkdirp/index.js:38:26
at Object.oncomplete (fs.js:107:15)

This makes no sense to me. It does render the page with the correct values in the fields, but I can't submit the form. Ideas?

Upvotes: 1

Views: 1084

Answers (1)

ubik
ubik

Reputation: 4560

By using:

app.param('name', function (req, res, next, name){
  //...
});

You are mapping a parameter name to a user retrieved from the DB. You are currently extracting this parameter from your URLs:

app.get('/users/:name/edit', function (req, res){
  // ...
});

The :name token tells Express that it should invoke the code above and retrieve a user that will get saved in the request address.

The form in your template, however, makes a request to /users/, and no user is specified. So, either you generate the correct URL for your form:

form(method="POST", action="/users/#{user.name}/xxx")

Or the method will fail.

I don't know the specifics of the tutorial, but I guess there should be another request handler that saves these parameters into the DB.

Upvotes: 1

Related Questions