Home > Backend Development > PHP Tutorial > Could you please repackage the result of request using fetch api library?

Could you please repackage the result of request using fetch api library?

WBOY
Release: 2016-10-11 14:23:44
Original
1296 people have browsed it

Hello everyone, I use this library https://github.com/dvajs/dva/... When requesting the rest api of yii2, how can I get the header returned by the serverx-pagination-page-count, x-pagination -Total-count and other information are packaged into the returned results?

The header of the current API return information already contains the following information

<code>x-pagination-current-page:1
x-pagination-page-count:35
x-pagination-per-page:12
x-pagination-total-count:411</code>
Copy after login
Copy after login

I hope to repackage the returned data so that the data object contains list (the original return result), x-pagination-total-count, x-pagination-page-count. and other information of the server header information

But now I can only get that the pure rest return result is an array. I tried to re-encapsulate the data in the request class, but all attempts failed. Various searches, maybe the keywords are wrong, and no solution was found.

Could you please tell me how can I package it into the object I need? Thank you!!!

The request code is as follows:

<code> const {data} = yield call(query, parse(payload));
      if (data) {
        console.log(data); //!!!这里!!!  我希望将这里返回的data 重新包装下,使data对象list, 服务器头信息,x-pagination-total-count,x-pagination-page-count.等信息 
        // 但是现在 我只能获取到, 纯粹的rest返回结果 是个数组. 我尝试在 request类中重新封装数据, 各种尝试都失败了. 各种搜  可能是关键词不对  也没有找到解决办法. 
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.list,
            total: Number(data.total),
            current: Number(data.current),
            pageSize: data.pageSize ? data.pageSize : 12,
          }
        });
      }</code>
Copy after login
Copy after login

The asynchronous methods are as follows:

<code>export async function query(params) {
  return request(`/api/users?${qs.stringify(params)}`);
}</code>
Copy after login
Copy after login

request class is as follows:

<code>import fetch from 'dva/fetch';

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    //这里是可以读取到这些信息的. 但是我不会重新包装. 
    console.log(response.headers.get('x-pagination-page-count')); //35
    console.log(response.headers.get('x-pagination-total-count')); //411
    return response;
  }
  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

function parseJSON(response) {

  return response.json();
}
/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then((data)=>({data}))
    .catch((err) => ({ err }));
}
</code>
Copy after login
Copy after login

yii2 rest controller is as follows:

<code><?php
namespace api\modules\test\controllers;

use yii;
use yii\helpers\ArrayHelper;
class UsersController extends yii\rest\ActiveController
{
    public $modelClass = '\common\models\User';
    public function behaviors() {
        return ArrayHelper::merge(parent::behaviors(), [
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
                'cors' => [
                    // restrict access to
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['*'],
                    'Access-Control-Request-Headers' => ['*'],
                    'Access-Control-Allow-Credentials' => true,
                    // Allow OPTIONS caching
                    'Access-Control-Max-Age' => 3600,
                    // Allow the X-Pagination-Current-Page header to be exposed to the browser.
                    'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
                ],
            ],
        ]);
    }

    public function actions()
    {
        $actions = parent::actions();
        // 禁用"delete" 和 "create" 操作
        unset($actions['delete'], $actions['create']);
        return $actions;
    }
}</code>
Copy after login
Copy after login

Reply content:

Hello everyone, I use this library https://github.com/dvajs/dva/... When requesting the rest api of yii2, how can I get the header returned by the serverx-pagination-page-count, x-pagination -Total-count and other information are packaged into the returned results?

The header of the current API return information already contains the following information

<code>x-pagination-current-page:1
x-pagination-page-count:35
x-pagination-per-page:12
x-pagination-total-count:411</code>
Copy after login
Copy after login

I hope to repackage the returned data so that the data object contains list (the original return result), x-pagination-total-count, x-pagination-page-count. and other information of the server header information

But now I can only get that the pure rest return result is an array. I tried to re-encapsulate the data in the request class, but all attempts failed. Various searches, maybe the keywords are wrong, and no solution was found.

Could you please tell me how can I package it into the object I need? Thank you!!!

The request code is as follows:

<code> const {data} = yield call(query, parse(payload));
      if (data) {
        console.log(data); //!!!这里!!!  我希望将这里返回的data 重新包装下,使data对象list, 服务器头信息,x-pagination-total-count,x-pagination-page-count.等信息 
        // 但是现在 我只能获取到, 纯粹的rest返回结果 是个数组. 我尝试在 request类中重新封装数据, 各种尝试都失败了. 各种搜  可能是关键词不对  也没有找到解决办法. 
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.list,
            total: Number(data.total),
            current: Number(data.current),
            pageSize: data.pageSize ? data.pageSize : 12,
          }
        });
      }</code>
Copy after login
Copy after login

Asynchronous methods are as follows:

<code>export async function query(params) {
  return request(`/api/users?${qs.stringify(params)}`);
}</code>
Copy after login
Copy after login

request class is as follows:

<code>import fetch from 'dva/fetch';

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    //这里是可以读取到这些信息的. 但是我不会重新包装. 
    console.log(response.headers.get('x-pagination-page-count')); //35
    console.log(response.headers.get('x-pagination-total-count')); //411
    return response;
  }
  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

function parseJSON(response) {

  return response.json();
}
/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then((data)=>({data}))
    .catch((err) => ({ err }));
}
</code>
Copy after login
Copy after login

yii2 rest controller is as follows:

<code><?php
namespace api\modules\test\controllers;

use yii;
use yii\helpers\ArrayHelper;
class UsersController extends yii\rest\ActiveController
{
    public $modelClass = '\common\models\User';
    public function behaviors() {
        return ArrayHelper::merge(parent::behaviors(), [
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
                'cors' => [
                    // restrict access to
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['*'],
                    'Access-Control-Request-Headers' => ['*'],
                    'Access-Control-Allow-Credentials' => true,
                    // Allow OPTIONS caching
                    'Access-Control-Max-Age' => 3600,
                    // Allow the X-Pagination-Current-Page header to be exposed to the browser.
                    'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
                ],
            ],
        ]);
    }

    public function actions()
    {
        $actions = parent::actions();
        // 禁用"delete" 和 "create" 操作
        unset($actions['delete'], $actions['create']);
        return $actions;
    }
}</code>
Copy after login
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template