自定义Drupal 8 REST资源上不允许POST方法

时间:2016-03-29 09:37:51

标签: drupal

我创建了一个自定义RestResource,它看起来像这样:

/**
 * Provides a resource to get/create content data.
 *
 * @RestResource(
 *   id = "arcelor_content",
 *   label = @Translation("Arcelor content"),
 *   uri_paths = {
 *     "canonical" = "/api/content/{type}"
 *   }
 * )
 */
class ContentResource extends ResourceBase {

    public function get($type) {
        // Works
    }

    public function post($type) {
        // Doesn't work
    }
}

我已启用资源并在RestUI中设置权限。

GET方法工作正常,但当我尝试发布时,我收到此错误:

{
"message": "No route found for \"POST /api/content/buffer\": Method Not Allowed (Allow: GET)"
}

方法不允许!即使已设置权限,已启用帖子,缓存已刷新一百万次,...

我遇到a question on the drupal site,说可以通过在phpdoc标签上添加另一个uri_path来修复它,所以我做了:

/**
 * Provides a resource to get/create content data.
 *
 * @RestResource(
 *   id = "arcelor_content",
 *   label = @Translation("Arcelor content"),
 *   uri_paths = {
 *     "canonical" = "/api/content/{type}",
 *     "https://www.drupal.org/link-relations/create" = "/api/content/{type}"
 *   }
 * )
 */

不幸的是,什么也没做,我仍然得到“不允许”的错误。

那么,有谁知道这里发生了什么?

2 个答案:

答案 0 :(得分:3)

有两件事导致了“不允许”的问题:

  1. POST方法要求Content-Type标头设置为application/hal+json,这是他们唯一接受的内容。即使您计划使用常规JSON数据执行不同的操作,您也必须以某种方式解决此问题(我没有做到这一点)
  2. POST方法还需要设置X-CSRF-Token标头,您可以转到/rest/session/token
  3. 获取令牌

    现在我不再收到“不允许”的错误!很遗憾,因为正文需要hal+json,我现在收到"A fatal error occurred: Class does not exist"错误。

答案 1 :(得分:1)

对我来说,在Drupal 8.2.6下,解决POST不允许方法的问题是我忘记在资源定义注释中指定create URI:

/**
 * Provides a resource for clients subscription to updates.
 *
 * @RestResource(
 *   id = "updates_subscription",
 *   label = @Translation("Updates subscription"),
 *   uri_paths = {
 *     "canonical" = "/api/updates-subscription",
 *     "https://www.drupal.org/link-relations/create" = "/api/updates-subscription"
 *   }
 * )
 */

事实是,如果您忘记指定"https://www.drupal.org/link-relations/create" URI路径,Drupal默认为资源ID路径,在这种情况下为updates_subscription

您可以在创建REST资源插件部分中阅读此here

application/hal+json内容类型无需使用X-CSRF-Token