简体   繁体   English

无法使用Node.js Express MongoDB Mongoose CoffeeScript进行POST

[英]Cannot POST with Node.js Express MongoDB Mongoose CoffeeScript

Update: I found the solution, look in the bottom of this page... 更新:我找到了解决方案,请查看本页底部...

I've got a Node.js, Express, MongoDB, Mongoose project written in CoffeScript and I can create and read data, but I can't update. 我有一个用CoffeScript编写的Node.js,Express,MongoDB,Mongoose项目,我可以创建和读取数据,但我无法更新。

This is what my code looks like; 这就是我的代码的样子;

app.js app.js

 # update
 app.put "/admin/:id.:format?", (req, res) ->
    Content.findById req.body.content.id, (err, c) ->
        c.title = req.body.content.title
        c.body = req.body.content.body
        c.save (err) ->
            switch req.params.format
                when "json"
                    res.send c.__doc
                else
                    res.redirect "/admin"

edit.jade edit.jade

h2 Edit Content
form(method='post', action='/admin/' + c.id)
  input(name='content[id]', value=c.id, type='hidden')
  input(name='_method', value='PUT', type='hidden')
div
  label Title:
    input(name='content[title]', value=c.title || '')
div
  label Body:
    textarea(name='content[body]')=c.body || ''
div
  input(type='submit', value='Save')

And this is what my console says 这就是我的控制台所说的

127.0.0.1 - - [Thu, 13 Oct 2011 21:39:55 GMT] "POST /admin/4e96ec17fd7da7cb18000001 HTTP/1.1" 404 - "http://localhost:1234/admin/4e96ec17fd7da7cb18000001/edit" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.83 Safari/535.2"

And this is what my browser tells me 这就是我的浏览器告诉我的内容

Cannot POST /admin/4e96ec17fd7da7cb18000001

表单向服务器发送POST请求,但您的路由是针对PUT请求的。

I found the solution on http://expressjs.com/guide.html : 我在http://expressjs.com/guide.html上找到了解决方案:

"When using methods such as PUT with a form, we can utilize a hidden input named _method, which can be used to alter the HTTP method. To do so we first need the methodOverride middleware, which should be placed below bodyParser so that it can utilize it's req.body containing the form values." “当使用带有表单的PUT等方法时,我们可以使用一个名为_method的隐藏输入,它可以用来改变HTTP方法。为此,我们首先需要使用methodOverride中间件, 它应该放在bodyParser下面,这样就可以了利用它包含表格值的req.body。“

app.use express.bodyParser()
app.use express.methodOverride()

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

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