首页 > 解决方案 > 如何使用 Strapi 创建自定义注册和登录 API?

问题描述

我正在使用 Strapi 创建 API。我想实现自己的注册 API 和登录 API。我检查了strapi的文档,但我没有找到任何自定义API。

谁可以帮我这个事?

标签: javascriptnode.jsstrapi

解决方案


相同的答案,但更详细:

Strapi 会自动为您创建一个 Auth 控制器,您可以覆盖它的行为。

register从此文件中复制您需要的功能(例如):

node_modules/strapi-plugin-users-permissions/controllers/Auth.js

至:

your_project_root/extensions/users-permissions/controllers/Auth.js

现在您可以覆盖该行为,例如在注册过程中传递一个自定义字段{"myCustomField": "hello world"}并将其记录到控制台:

async register(ctx) {
  ...
  ...
  // log the custom field
  console.log(params.myCustomField)

  // do something with it, e.g. check whether the value already exists
  // in another content type
  const itExists = await strapi.query('some-content-type').findOne({
    fieldName: params.myCustomField
  });
  if (!itExists) {
    return ctx.badRequest(...)
  } else {
    console.log('check success')
  }
}

推荐阅读