Background: I’m writing a little field plugin to retrieve some offsite data and store it as page content. And going to need to do that with a Remote::get
rather a js fetch()
in the front because, CORS, auth etc.
Here’s a minimal example:
plugin/src/index.js:
panel.plugin("my/test", {
fields: {
tester: {
template: `
<k-field :label="label">
<k-button
variant="filled"
@click="getStuff()"
>
getStuff
</k-button>
<k-button
variant="filled"
@click="callAFunc()"
>
callAFunc
</k-button>
</k-field>
`,
props: {
label: String,
},
methods: {
getStuff() {
this.$api.get("my/test/getStuff").then((response) => {
console.log(response);
});
},
callAFunc() {
console.log("calling a function");
this.$api.get("my/test/callMethod").then((response) => {
console.log(response);
});
},
},
},
},
});
plugin/index.php
<?php
use Kirby\Cms\App as Kirby;
Kirby::plugin('my/test', [
'fields' => [
'tester' => []
],
'api' => [
'routes' => function ($kirby) {
return [
[
'pattern' => 'my/test/getStuff',
'action' => function () {
return collection('latest/posts')->toArray();
// this works fine
}
], [
'pattern' => 'my/test/callMethod',
'action' => function () use ($kirby) {
return $kirby->site()->fetchData();
}
],
];
}
],
'siteMethods' => [
'fetchData' => function () {
$test = [
'test' => 'test'
];
return json_encode($test);
}
]
]);
The first call to an API route returns the collection data just fine.
But the second, where I call a siteMethod, gives me an authentication error:
{"status":"error","message":"Unauthenticated","code":401,"exception":"Kirby\\Exception\\AuthException","key":"error.auth","file":"..\/vendor\/getkirby\/cms\/config\/api\/authentication.php","line":14,"details":[],"route":"my\/test\/callMethod"}
I can’t for the life of me see why, if it’s hitting the api endpoint in the same way, it needs different authentication to use a site method. What am I missing???