Egg.js项目中resources的patch方法无法生效
发布于 4 年前 作者 yangjindong 3886 次浏览 来自 问答

最近遇到一个奇怪的问题,那位大神帮看一下: 在一个egg项目中,router中定义了一个resources, router.js

router.resources(‘admin_roles’, ‘/admin/roles’, controller.admin.roles);

用form表单提交数据,在编辑数据时,使用restful默认的patch方法:method=“patch”, app/view/roles/edit.html

<form action="/admin/roles/<%=list._id%>" method=“patch”> <ul> <input type=“hidden” name="_csrf" value="<%=csrf%>" /> <li>角色名称: <input type=“text” name=“title” value="<%=list.title%>" /></li> <li>角色描述:<textarea name=“description” id="" cols=“60” rows=“8”><%=list.description%></textarea></li> <li><input type=“submit” value=“提交” class=“btn btn-default”></li> </ul> </form>

但提交后却变为get请求,返回404

Request URL: http://localhost:7001/admin/roles/5e0d52943855f76d3c88ddc1?_csrf=LpHNef1e-H5YPfmaRq4Up6vxuo8djj8YR0UQ&title=aaa3333&description=333333 Request Method: GET Status Code: 404 Not Found Remote Address: [::1]:7001 Referrer Policy: no-referrer-when-downgrade

不知是哪里出了问题? 谢谢!

5 回复

404是没有找到资源,一般情况下为请求路径问题,看一下后台路由配置,以及是否做静态资源托管

@Limiandy 根据你的回复,重新检查了一下。原来提交了之后,是直接跳转到了roles的resources路由的show方法,但这个方法没有定义和设置,所以返回404。 但这也并不是自己所期望的,所期望的是进入update方法。

formmethod 只有 3 个值:https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fs-method

  • get
  • post
  • dialog

The invalid value default for these attributes is the GET state.

@justjavac 根据你的回复,又查看了下Ruby on Rails里关于form_for的文档:

:method - The method to use when submitting the form, usually either “get” or “post”. If “patch”, “put”, “delete”, or another verb is used, a hidden input with name _method is added to simulate the verb over post.

原来restful api里patch方法,在form表单里是这么解决的。 所以,在此也就添加了一个隐藏的input。

<form action="/admin/roles/<%=list._id%>" method=“post”> <ul> <input type=“hidden” name="_method" value=“patch” /> <input type=“hidden” name="_csrf" value="<%=csrf%>" /> <li>角色名称: <input type=“text” name=“title” value="<%=list.title%>" /></li> <li>角色描述:<textarea name=“description” id="" cols=“60” rows=“8”><%=list.description%></textarea></li> <li><input type=“submit” value=“提交” class=“btn btn-default”></li> </ul> </form>

问题解决。多谢各位🙏

回到顶部