我知道 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 功能之前的一种解决方法,我们不能指望在短时间内完成