nazirov91/ra-strapi-rest

User model CORS error

Closed this issue · 2 comments

Hello,

In the README, you state that we must update the controller for each model we have, overriding the async find method in the controller file. However, Since the user model is automatically included with Strapi, there is no controller file for the user model. How do you suppose we get rid of the cors error associated when trying to access the user data.

@Ethanpolley You can override the user controller in the extensions folder

  1. Create a folder named controllers inside <your_strapi_project>/extensions/user-permissions
  2. Inside the newly created controllers folder create a new js file called User.js
  3. Add the following code inside
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 = {
  /**
   * Retrieve user records.
   * @return {Object|Array}
   */
  async find(ctx, next, { populate } = {}) {
    let users;
    ctx.set(
      "Content-Range",
      await strapi.query("user", "users-permissions").count({})
    );
    if (_.has(ctx.query, "_q")) {
      // use core strapi query to search for users
      users = await strapi
        .query("user", "users-permissions")
        .search(ctx.query, populate);
    } else {
      users = await strapi.plugins["users-permissions"].services.user.fetchAll(
        ctx.query,
        populate
      );
    }

    const data = users.map(sanitizeUser);
    ctx.send(data);
  }
};
  1. Profit

@Ethanpolley If the solution given above does not resolve your problem you are welcome to re-open this issue.

Thanks!