【问题标题】:How to update me endpoint in Strapi?如何在 Strapi 中更新我的端点?
【发布时间】:2021-01-10 14:14:09
【问题描述】:

我正在为一个项目使用 Strapi v3.4.0。我想允许经过身份验证的用户在点击以下端点时更新他的个人信息:

PUT /users/me

现在我只是想在到达端点时控制台记录一条消息,我已按照此视频中的步骤操作:https://www.youtube.com/watch?v=ITk-pYtOCnQ 但我不断收到 403 错误“禁止”。我做错了吗?

【问题讨论】:

    标签: content-management-system strapi headless-cms


    【解决方案1】:

    我知道 Strapi 中的这个更新我的问题真的很痛苦。由于 Strapi 刚刚更新到新版本,我也按照您上面放置的链接上的教程无济于事。我为此解决方案尝试了一种解决方法。所以基本上,我尝试在 api 文件夹上显示的模型上创建一个额外的方法(以前,我试图在用户控制器上添加一个新方法,但我又得到了这个 403 错误)。至于我的方法,我创建了一个名为 User Profile 的模型,然后添加了用于更新当前用户数据的自定义方法,如下所示。

    api/user-profile/config/routes.json

    ...
    {
      "method": "PUT",
      "path": "/updateMe",
      "handler": "user-profile.updateMe",
      "config": {
        "policies": []
      }
    },
    {
      "method": "PUT",
      "path": "/user-profiles/:id",
      "handler": "user-profile.update",
      "config": {
        "policies": []
      }
    }
    ...
    

    在控制器上,我添加了以下sn-ps

    api/user-profile/controllers/user-profile.js

    'use strict';
    
     const _ = require('lodash');
     const { sanitizeEntity } = require('strapi-utils');
     
     const sanitizeUser = user =>
       sanitizeEntity(user, {
         model: strapi.query('user', 'users-permissions').model,
       });
     
     const formatError = error => [
       { messages: [{ id: error.id, message: error.message, field: error.field }] },
     ];
     
    
    module.exports = {
        async updateMe(ctx) {
            const { id } = ctx.state.user;
    
            let updateData = {
                ...ctx.request.body,
            };
    
            const data = await strapi.plugins['users-permissions'].services.user.edit({ id }, updateData);
    
            ctx.send(sanitizeUser(data));
        },
    };
    

    之后,启用 updateMe 供公众使用(现在,您不必担心,因为ctx.state.user 行会检查令牌是否有效,{ 至少在开发人员正式创建此 updateMe 函数之前})

    就是这样。您只需将属性传递给正文和身份验证标头即可。你几乎可以把函数放在任何你想要的地方

    PS:请注意,您必须将 updateMe 路由放在更新路由之上。否则,它会给你同样的 403 错误

    PPS:这只是在开发者正式包含 updateMe 功能之前的一种解决方法,我们不能指望在短时间内完成

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-04
      • 2022-08-22
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 2022-07-08
      相关资源
      最近更新 更多