System Information
- Strapi Version: 3.6.2
- Operating System: Ubuntu 20.04
- Database: Mysql
- Node Version: 12.19
- NPM Version: 6.14.11
- Yarn Version: 1.22.5
Hi,
I’m trying to make a POST request from a component in my custom plugin. I defined the route, the controller, the service and the policy I want this request to send to. But I’m struggling with my policy because I want this request to be executed only if you are an administrator and I’m getting
error TypeError: Cannot read property 'role' of undefined
So I cannot get the user in the policy context. Based on the example on Strapi documentation, here is my policy
plugins/dataImport/config/policies/isAdmin.js :
module.exports = async (ctx, next) => {
if (ctx.state.user.role.name === 'Administrator') {
// Go to next policy or will reach the controller's action.
return await next();
}
ctx.unauthorized(`You're not allowed to perform this action!`);
};
Here is my plugin routes :
{
"routes": [
{
"method": "GET",
"path": "/",
"handler": "data-import.index",
"config": {
"policies": []
}
},
{
"method": "POST",
"path": "/import",
"handler": "data-import.import",
"config": {
"policies": ["isAdmin"]
}
}
]
}
And here is my React component (in the plugin) :
import React, { Component } from “react”;
import axios from “axios”;
class DataImportForm extends Component {
constructor(props) {
super(props);
}
handleChange = (event) => {
axios.post("/data-import/import").then((response) => {
console.log(response);
});
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleChange}>
<button type="submit" class="btn btn-primary hxsPO">Import data</button>
</form>
);
}
}
export default DataImportForm;
Thank you for you help.