【问题标题】:VueJs 2 and Symfony 3 Patch Rest RequestVueJs 2 和 Symfony 3 补丁休息请求
【发布时间】:2018-05-26 17:56:16
【问题描述】:

我的目标是发出一个事件请求 PATCH,使用 VueJs 2 触发以下内容:

// Link and body is defined and fine
this.$http.patch(linkUrl, this.baseTerms, {someKey:'any value'}).then(response => {
      console.log(response.body)
   }, response => {
 })

另一方面,该请求被 Symfony 3 - FosRestBundle 捕获,例如:

/**
 * @Rest\Patch("/translations/update-base-delta/", name="update_base_delta")
 */
public function updateBaseDeltaAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $postData = json_decode($request->getContent(), true);
}

// config.yml:
fos_rest:
    unauthorized_challenge: "Basic realm=\"Restricted Area\""
    access_denied_listener:
        json: true
    routing_loader:
        default_format: json

这样的结果是:状态码:405 方法不允许

这是请求:

Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-GB,en-US;q=0.9,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:PATCH
Connection:keep-alive

已经提到缺少的查询字符串参数和请求标头。 谁能提示我一个可行的例子或告诉我,在哪一部分专注于 VueJs 或 Symfony?

【问题讨论】:

  • 仔细检查您在 chrome 开发工具中请求的网址
  • 请求转到:/translations/update-base-delta/ 在服务器端:@Rest\Patch("/translations/update-base-delta/", name="update_base_delta")两个 URL 匹配。

标签: php rest symfony vue.js vuejs2


【解决方案1】:

我发现出了什么问题以及如何实现这一切。 - VueJs 2 的请求:

this.$http.patch(linkUrl, {somePara: 123}).then(response => {
      console.log(response.body)
    }, response => {
})

// 请注意,Patch 需要一个预检程序 (CORS),它首先发送一个 OPTIONS 请求,并带有以下要求的标头键:

  • 访问控制允许来源
  • 访问控制允许方法
  • 访问控制允许标头

响应部分:服务器端也必须遵循这个预检程序。首先,检查 OPTIONS 和要求是否满足 -> 发送提到的 Header Keys,其次:对请求做出反应。

这里是 Symfony 3 和 Fos Rest Bundle 集成示例:

    /**
     * @Options("/translations/update-base-delta/")
    */
    public function preflightMyPatchAction(Request $request)
    {    
        $response = new Response(); 
        $response->setContent(json_encode(true));
        $response->headers->set('Access-Control-Allow-Methods', 'PATCH');
        $response->headers->set('Access-Control-Allow-Origin', '*');
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type');
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    /**
     * @Patch("/translations/update-base-delta/")
    */
    public function myPatchAction(Request $request)
    {    
        $response = new Response(); 
        $response->setContent(json_encode(true));
        $data = json_decode($request->getContent(), true);
        return $response;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多