Reputation: 41
I am trying to find a 'native' way to send post requests to my pocketbase server, from my svelte frontend :
main.go:
app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
e.Router.AddRoute(echo.Route{
Method: http.MethodPost,
Path: "/api/myRoute",
Handler: func(c echo.Context) error {
// custom logic here: compute custom_value using parameters
custom_value := "cool_value"
return c.String(200, custom_value)
},
})
return nil
})
I would like to do something similar to the following :
Frontend.ts:
onMount(async () => {
// ask server for information based on a variable: example
const example = "test";
const example_reply = await pb.route(POST, '/api/myRoute', /*here, I would have to specify the fact that example is a form value of the POST request*/ example);
// use example_reply
if (example_reply === "cool_value") {
console.log('got what I expected');
} else {
console.log('wrong!!!');
}
}
Does the function I am looking for exist, or should I use raw JS to fetch information from my custom routes ?
I have tried to use raw javascript to send a post request, which works but does not use the pocketbase package. :
const response = await fetch('/api/example', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ example: "test" }), // Convert the input to JSON
});
Upvotes: 0
Views: 1654
Reputation: 2402
In the routing documentation at the very end they have this:
import PocketBase from 'pocketbase';
const pb = new PocketBase('http://127.0.0.1:8090');
await pb.send("/hello", {
// for all possible options check
// https://developer.mozilla.org/en-US/docs/Web/API/fetch#options
query: { "abc": 123 },
});
PocketBase Routing Documentation...
You can find the hello
sample on the page or access the one you created. They expose the custom routes via the SDK using the send()
method.
Upvotes: 1
Reputation: 41
The way to send request to custom pocketbase routes using javascript is the one mentioned in the question, with some adjustments :
const formData = new URLSearchParams();
formData.append('custom_param', 'custom_param_value');
const response = await fetch(pb.baseUrl + '/api/customRoute', {
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded',
},
body: formData.toString(),
});
if (!response.ok)
{
throw new Error('');
}
const data: string = await response.text();
Indeed, Pocketbase custom routes are not meant to be accessed through the client-side sdk, but rather to allow other components of your project to access server-side information and logic WITHOUT going using the sdk.
Upvotes: 1