我们先来创建一个接口,然后看一下正常接口返回的数据格式是什么样子

创建表以及字段

添加一条数据

配置接口权限

我暂时给了这个接口PUBLIC权限,用来测试
strapi系列-如何去除接口里的attributes以及 data key,配置关联数据等-小白菜博客

使用postman进行接口测试

我们可以看到,这里被包了一层attributes,如果我们想要去掉这一层,如何处理呢

  • 方案一:写一个middleware对接口数据进行处理
  • 方案二:使用strapi-plugin-transformer插件,简单配置即可轻松解决,

下面我们采用strapi-plugin-transformer进行数据处理测试

参考文档:https://www.npmjs.com/package/strapi-plugin-transformer

strapi-plugin-transformer介绍

A plugin for Strapi that provides the ability to transform the API request and/or response.

下载安装

npm install strapi-plugin-transformer
# OR
yarn add strapi-plugin-transformer

打开项目中./config/plugins.js文件,如果不存在,创建它,配置如下

  • 我的项目是ts类型,所以我创建的是plugins.ts
  • 一旦插件被安装、配置和启用,任何对Strapi API的请求都将自动转换
  • 此响应转换将从响应中删除attributes属性键,并将其所有属性上移一级。
module.exports = ({ env }) => ({
   'transformer': {
      enabled: true,
      config: {
        prefix: '/api/',
        responseTransforms: {
          removeAttributesKey: true,
          removeDataKey: true,
        }
      }
    },
  });

服务刷新以后,重新接口测试,我们可以发现已经实现了我们想要的功能

下面的情况需要注意

strapi系列-如何去除接口里的attributes以及 data key,配置关联数据等-小白菜博客
strapi系列-如何去除接口里的attributes以及 data key,配置关联数据等-小白菜博客

我们创建一个关系型数据来进行测试

strapi系列-如何去除接口里的attributes以及 data key,配置关联数据等-小白菜博客

strapi 从v3版本升级到v4后,api默认响应数据不返回关系数据,本次我们测试,先在接口请求时添加 pouplate 参数,参数后面为*,显示所有关系数据

参看文档说明:https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#endpoints
访问:http://localhost:1337/api/terms-infos?populate=*

下图是去掉配置和加上配置的对比效果 Remove the data key

我们还可以设置忽略

大功告成~

  • 今天就写到这里啦~小伙伴们,( ̄ω ̄( ̄ω ̄〃 ( ̄ω ̄〃)ゝ我们明天再见啦~~
  • 大家要天天开心哦

欢迎大家指出文章需要改正之处~
学无止境,合作共赢

在这里插入图片描述

欢迎路过的小哥哥小姐姐们提出更好的意见哇~~