【问题标题】:Am trying to use fetchApi to fetch data but i get this error我正在尝试使用 fetchApi 来获取数据,但我收到了这个错误
【发布时间】:2018-07-31 05:14:45
【问题描述】:

运行代码后出现错误 SyntaxError:位置 1 的 JSON 中的意外标记

这是我检查响应状态的代码..

function checkStatus(response){
  'use strict';
  if(response.ok){
   return response;
  }

  let error = new Error(response.statusText);
  error.response = response;
  return Promise.reject(error);
}

这是获取数据的代码..

function fetchApiData(){
    'use strict';
    const url = '/dashboard/getDataFarmersPerYear';

    fetch (url)
    .then(checkStatus)
    .then (response =>response.json())
    .then (data =>{
      console.log(data);

    })
    .catch((error) => {
      console.log('There was an error', error);
    });
}

试图从中获取数据的终点在这里

public function getDataFarmersPerYear()
{
    if ($this->request->is('ajax')) {
        $data = $this->Dashboard->getDataFarmersPerYear();

        $this->set('data', $data);
        $this->set(
            '_serialize',
            'data'
        );
    }
}

【问题讨论】:

  • 听起来您的服务器没有返回有效的 JSON。 (检查您的网络标签)
  • @CertainPerformance 你是对的.. 当我使用 arrayBuffer() 而不是 json() 时没有错误。
  • 打赌你会得到 HTML
  • 不……不是……@JaromandaX
  • 那么你收到了什么?

标签: javascript cakephp ecmascript-6 es6-promise


【解决方案1】:

尝试更改以下行

.then (response =>response.json())

.then (response =>alert(JSON.stringify(response)))

您将收到有关响应中存在 html 错误的警报消息

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-10-25
  • 2021-07-08
  • 1970-01-01
  • 1970-01-01
  • 2023-02-10
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
相关资源
最近更新 更多