如何解决如何在 Strapi 中更新我的端点?
我正在使用 Strapi v3.4.0 进行一个项目。我想允许经过身份验证的用户在点击以下端点时更新他的个人信息:
PUT /users/me
现在我只是想在到达端点时控制台.log 一条消息,我已按照此视频中的步骤操作:https://www.youtube.com/watch?v=ITk-pYtOCnQ 但我不断收到 403 错误“禁止”。我做错了什么吗?
解决方法
我知道 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": []
}
}
...
在控制器上,我添加了以下代码片段
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 功能,这是我们短时间内无法预料的
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。