【问题标题】:Json Cannot be ParsedJson 无法解析
【发布时间】:2021-11-28 04:42:57
【问题描述】:

我正在尝试使用 Guzzle laravel 发布一个对象,我使用表单提交从我的视图中传递它,但是当我这样做时它说 INVALID FORMAT Json 无法解析

我的观点

            <form method="POST" action="comparePrices">
                @csrf
                <input type="text" name="datas" id="textsss"/>
                <input type="submit" value="save"/>
            </form>

但是当我通过邮递员发布它时,它工作正常

我的控制器

        public function comparePrices(Request $request)
    {
        $token = DB::table('a_p_is_tokens')->select('*')->limit(1)->orderBy('id', 'desc')->get()->pluck('token')[0];
        $client = new Client();

        try {
            $res = $client->post('https://test.api.amadeus.com/v1/shopping/flight-offers/pricing', [

                'headers' => [
                    'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $token,
                ],
                'form_params' => [
                    "data"=>[
                        "type" => "flight-offers-pricing",
                        "flightOffers" => $request->datas,
                    ],
                // 'body'    => array('data'=>$items),
            ]);

            $res = json_decode($res->getBody()->getContents(), true);
            $response = $res->getResponse();

            print_r(json_decode($response->getBody(), true));
            // return view('agents.agentsTickets');
        } catch (RequestException $e) {
            $response = $e->getResponse();
            $result =  json_decode($response->getBody()->getContents());
            return response()->json(['data' => $result]);
            // return [json_decode($request->datas)];

        }
        dd([$items]);
        return view('agents.agentsTickets');
    }

错误代码

{
  "data": {
    "errors": [
      {
        "code": 477,
        "title": "INVALID FORMAT",
        "detail": "JSON cannot be parsed",
        "status": 400
      }
    ]
  }
}

【问题讨论】:

  • 你为什么要把这个长度的数据作为 URL 参数传递?您可能面临达到普通客户端允许的 URL 大小限制的危险。 (而且您甚至没有应用正确的 URL 编码。)
  • 另外我想知道,该错误消息是否实际上应该意味着 JSON 是 invalid - 或者它是否可能只是告诉你,你是什么数据发送是结构化错误的。
  • 您尝试过什么来解决问题?你被困在哪里了?您是否检查过 Postman 所做的事情是否与 Guzzle 不同?
  • ....例如:为什么您在 Postman 中的请求以 data 键开头,而您的 Guzzle 请求却没有?
  • 谢谢大家指出我的错误现在我通过表单发送数据但仍然出现同样的错误

标签: php laravel postman guzzle


【解决方案1】:

您的 js 代码执行 http GET 而不是 http POST

window.location='postings/'+items;

如果应该可以在 url abd perform http GET 中添加“项目”,那么您可以尝试在 Postman 中执行相同的操作 - 使用 GET 而不是 POST 并修改 url,而不是正文。

如果您打算在 js 中执行与 Postman 相同的操作,那么我建议您查看 pass post data with window.location.href 的答案并修改您的 js 代码。或者试试https://reqbin.com/req/javascript/uzf79ewc/javascript-post-request-example

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多