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
});
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.