Un fichier +page.server.js peut exporter des actions, ce qui vous permet d’envoyer des données
avec POST vers le serveur en utilisant un élément de formulaire <form>.
Lorsque vous utilisez un élément <form>, la présence de JavaScript côté client est optionnelle,
mais vous pouvez facilement améliorer progressivement vos interactions de formulaire avec
JavaScript pour fournir la meilleure expérience utilisateur.
La fonction distante expérimentale form couvre les mêmes cas
d’usage que les actions de formulaire, en y ajoutant du typage et des mutations
single-flight. Les actions de formulaire sont
polyvalentes et vont continuer de fonctionner, mais les nouveaux développements sont focalisés sur
les fonctions distantes, qui sont conçues pour devenir la méthode recommandée de communiquer avec
le serveur. Vous pouvez envisager l’usage des fonctions distantes pour vos nouveaux projets, en
gardant à l’esprit que l’API peut changer tant que cette fonctionnalité est expérimentale.
Actions par défaut
Dans le cas le plus simple, une page déclare une action par défaut appelée default :
={default(property)default:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>:async(event(parameter)event:RequestEvent<Record<string,any>,string|null>)=>{ // TODO identifier l'utilisateur
}};
importtype{Actions(alias)typeActions={[x:string]:Action<Record<string,any>,void|Record<string,any>,string|null>;}importActions}from'./$types';exportconstactionsconstactions:{default:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>;}={default(property)default:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>:async(event(parameter)event:RequestEvent<Record<string,any>,string|null>)=>{ // TODO identifier l'utilisateur
}}satisfiesActions(alias)typeActions={[x:string]:Action<Record<string,any>,void|Record<string,any>,string|null>;}importActions;
Pour invoquer cette action depuis la page /login, ajouter simplement un élément <form> — aucun
JavaScript n’est nécessaire :
src/routes/login/+page
<formmethod="POST"><label>Email<inputname="email"type="email"></label><label>Mot de passe<inputname="password"type="password"></label><button>Se connecter</button></form>
Lorsque le bouton est cliqué, le navigateur va envoyer au serveur les données du formulaire via une
requête POST, en exécutant l’action par défaut.
Les actions utilisent toujours des requêtes POST, puisque les requêtes GET ne sont pas
censées avoir d’effets de bord.
Nous pouvons aussi invoquer l’action depuis d’autres pages (par exemple, s’il y a un widget de
connexion dans la barre de navigation du layout racine) en ajoutant l’attribut action pointant
vers la page :
={default: async (event) => {login(property)login:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>:async(event(parameter)event:RequestEvent<Record<string,any>,string|null>)=>{ // TODO connecter l'utilisateur
},register(property)register:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>:async(event(parameter)event:RequestEvent<Record<string,any>,string|null>)=>{// TODO inscrire l'utilisateur}};
importtype{Actions(alias)typeActions={[x:string]:Action<Record<string,any>,void|Record<string,any>,string|null>;}importActions}from'./$types';exportconstactionsconstactions:{login:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>;register:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>;}={default: async (event) => {login(property)login:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>:async(event(parameter)event:RequestEvent<Record<string,any>,string|null>)=>{ // TODO connecter l'utilisateur
},register(property)register:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>:async(event(parameter)event:RequestEvent<Record<string,any>,string|null>)=>{// TODO inscrire l'utilisateur}}satisfiesActions(alias)typeActions={[x:string]:Action<Record<string,any>,void|Record<string,any>,string|null>;}importActions;
Pour invoquer une action nommée, ajoutez un paramètre de requête comportant le nom de l’action
préfixé par un caractère / :
src/routes/login/+page
<formmethod="POST"action="?/register">
src/routes/+layout
<formmethod="POST"action="/login?/register">
Similaire à l’attribut action, nous pouvons utiliser l’attribut formaction sur un bouton pour
envoyer avec POST les mêmes données de formulaire à une action différente de celle de l’élément
<form> parent :
src/routes/login/+page
<formmethod="POST"action="?/login"><label>Email<inputname="email"type="email"></label><label>Mot de passe<inputname="password"type="password"></label><button>Se connecter</button><buttonformaction="?/register">S'inscrire</button></form>
Il n’est pas possible d’avoir des actions par défaut dans le même fichier que des actions
nommées, car si vous ciblez une action nommée avec POST sans redirection, le paramètre de requête
est persisté dans l’URL, ce qui signifie que la prochaine requête POST par défaut va cibler
l’action nommée précédente.
Anatomie d’une action
Chaque action reçoit un objet RequestEvent, vous permettant de lire les données avec
request.formData(). Après le traitement de la requête (par exemple, pour connecter l’utilisateur
ou l’utilisatrice en définissant un cookie), l’action peut répondre avec des données qui seront
disponibles via la propriété form sur la page correspondante, et via page.form dans toute
l’application, jusqu’à sa prochaine mise à jour.
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
Sets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.
The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
name
the name of the cookie
value
the cookie value
opts
the options, passed directly to cookie.serialize. See documentation here
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
Sets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.
The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
name
the name of the cookie
value
the cookie value
opts
the options, passed directly to cookie.serialize. See documentation here
:'/'});return{success(property)success:boolean:true};},register(property)register:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>:async(event(parameter)event:RequestEvent<Record<string,any>,string|null>)=>{ // TODO inscrire l'utilisateur
}}satisfiesActions(alias)typeActions={[x:string]:Action<Record<string,any>,void|Record<string,any>,string|null>;}importActions;
src/routes/login/+page
<script>/**@type{import('./$types').PageProps}*/let{data,form}=$props();</script>{#ifform?.success}<!-- ce message est éphémère ; il existe car la page a été rendu en réponse à une soumissionde formulaire. il disparaîtra si l'utilisateur recharge la page --><p>Connexion réussie ! Content de vous revoir, {data.user.name}</p>{/if}
<scriptlang="ts">importtype{PageProps}from'./$types';let{data,form}:PageProps=$props();</script>{#ifform?.success}<!-- ce message est éphémère ; il existe car la page a été rendu en réponse à une soumissionde formulaire. il disparaîtra si l'utilisateur recharge la page --><p>Connexion réussie ! Content de vous revoir, {data.user.name}</p>{/if}
Legacy mode
PageProps a été ajouté dans la version 2.16.0 de SvelteKit. Dans les versions antérieures, vous
deviez typer les propriétés data et form individuellement :
Avec Svelte 4, vous utiliseriez plutôt export let data et export let form pour déclarer les
propriétés.
Erreurs de validation
Si la requête n’a pas pu être traitée à cause de données non valides, vous pouvez renvoyer des
erreurs de validation — en plus des valeurs précédemment soumises par le formulaire — à
l’utilisateur ou l’utilisatrice afin qu’il ou elle ré-essaye. La fonction fail vous permet de
renvoyer un statut HTTP (généralement 400 ou 422, dans le cas d’erreurs de validation) avec les
données. Le statut est rendu disponible via page.status et les données via form :
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
Sets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.
The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
name
the name of the cookie
value
the cookie value
opts
the options, passed directly to cookie.serialize. See documentation here
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
Sets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.
The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
name
the name of the cookie
value
the cookie value
opts
the options, passed directly to cookie.serialize. See documentation here
:'/'});return{success(property)success:boolean:true};},register(property)register:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>:async(event(parameter)event:RequestEvent<Record<string,any>,string|null>)=>{ // TODO inscrire l'utilisateur
}}satisfiesActions(alias)typeActions={[x:string]:Action<Record<string,any>,void|Record<string,any>,string|null>;}importActions;
Notez que par précaution, nous renvoyons uniquement l’email à la page — pas le mot de
passe.
src/routes/login/+page
<formmethod="POST"action="?/login">{#ifform?.missing}<pclass="error">Le champ email est requis</p>{/if}{#ifform?.incorrect}<pclass="error">Identifiants invalides !</p>{/if}<label>Email<inputname="email"type="email"value={form?.email??''}></label><label>Mot de passe<inputname="password"type="password"></label><button>Se connecter</button><buttonformaction="?/register">S'inscrire</button></form>
Les données renvoyées doivent être sérialisables en JSON. À part ça, la structure est complètement
libre. Par exemple, si vous avez plusieurs formulaires sur la même page, vous pourriez différencier
à quel élément <form> les données form font référence avec une propriété id ou similaire.
Redirections
Les redirections (et les erreurs) fonctionnent exactement de la même façon que dans
load :
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
Sets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.
The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
name
the name of the cookie
value
the cookie value
opts
the options, passed directly to cookie.serialize. See documentation here
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
The searchParams read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
The searchParams read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead.
Sets a cookie. This will add a set-cookie header to the response, but also make the cookie available via cookies.get or cookies.getAll during the current request.
The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
name
the name of the cookie
value
the cookie value
opts
the options, passed directly to cookie.serialize. See documentation here
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
The searchParams read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
Redirect a request. When called during request handling, SvelteKit will return a redirect response.
Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
Most common status codes:
303 See Other: redirect as a GET request (often used after a form POST request)
307 Temporary Redirect: redirect will keep the request method
308 Permanent Redirect: redirect will keep the request method, SEO will be transferred to the new page
In the context of a remote function request initiated by the client, this relates to the page the remote function
was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use this to determine
whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
The searchParams read-only property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
('redirectTo'));}return{success(property)success:boolean:true};},register(property)register:(event:RequestEvent<Record<string,any>,string|null>)=>Promise<void>:async(event(parameter)event:RequestEvent<Record<string,any>,string|null>)=>{ // TODO inscrire l'utilisateur
}}satisfiesActions(alias)typeActions={[x:string]:Action<Record<string,any>,void|Record<string,any>,string|null>;}importActions;
Chargement de données
Après l’exécution d’une action, la page sera re-rendue (à moins qu’une redirection ou une erreur
inattendue se produise), avec la valeur de retour de l’action rendue disponible dans la page en tant
que propriété form. Ceci signifie que les fonctions load de la page vont être exécutées après
la fin de l’exécution d’une action.
Notez que handle est exécuté avant l’invocation de l’action, et n’est pas ré-exécutée avant les
fonctions load. Ceci signifie que si, par exemple, vous utiliser handle pour remplir
event.locals en fonction d’un cookie, vous devez mettre à jour event.locals lorsque vous
définissez ou supprimez le cookie lors d’une action :
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
The handle hook runs every time the SvelteKit server receives a request and
determines the response.
It receives an event object representing the request and a function called resolve, which renders the route and generates a Response.
This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).
Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
name
the name of the cookie
opts
the options, passed directly to cookie.serialize. The path must match the path of the cookie you want to delete. See documentation here
Deletes a cookie by setting its value to an empty string and setting the expiry date in the past.
You must specify a path for the cookie. In most cases you should explicitly set path: '/' to make the cookie available throughout your app. You can use relative paths, or set path: '' to make the cookie only available on the current path and its children
name
the name of the cookie
opts
the options, passed directly to cookie.serialize. The path must match the path of the cookie you want to delete. See documentation here
Dans les sections précédentes, nous avons construit une action /login qui fonctionne sans
JavaScript côté client — aucun fetch n’a
été impliqué. C’est super, mais lorsque JavaScript est disponible, nous pouvons améliorer
progressivement nos interactions de formulaire pour fournir une meilleure expérience utilisateur.
use:enhance
La manière la plus simple d’améliorer un formulaire progressivement est d’ajouter l’action
use:action :
use:enhance peut uniquement être utilisé avec des formulaires qui ont method="POST" et
pointent vers des actions définies dans un fichier +page.server.js. Cela ne fonctionnera pas
avec method="GET", qui est le fonctionnement par défaut pour des formulaires sans méthode
précisée. Utiliser use:enhance sur des formulaires sans method="POST" ou cibler un endpoint
+server.js va provoquer une erreur.
Oui, il peut y avoir de la confusion entre l’action enhance et <form action>, qui sont
toutes les deux appelées “action”. Cette documentation est pleine d’actions. Désolé.
Sans argument, use:enhance va émuler le comportement natif du navigateur, simplement sans le
rechargement complet de la page. Plus précisément, cela va :
mettre à jour la propriété form, ainsi que page.form et page.status lors d’une réponse
réussie ou invalide, mais uniquement si l’action est sur la même page que celle depuis laquelle vous
soumettez. Par exemple, si vous formulaire ressemble à <form action="/somewhere/else" ..>, la
propriété form et l’état page.form ne seront pas mis à jour. En effet, la soumission native
d’un formulaire vous redirige vers la page sur laquelle l’action est définie. Si vous souhaitez tout
de même les mettre à jour, vous devez utiliser
applyAction
réinitialiser l’élément <form>
invalider toutes les données avec invalidateAll si la réponse est réussie
appeler goto si la réponse est une redirection
afficher la frontière d’erreur +error la plus proche si une erreur se produit
Pour personnaliser le comportement, vous pouvez fournir une SubmitFunction qui sera exécutée
immédiatement avant la soumission du formulaire, et (optionnellement) renvoyer un callback qui
fournira une ActionResult.
<formmethod="POST"use:enhance={({formElement,formData,action,cancel,submitter})=>{// `formElement` est l'élément`<form>`// `formData` est son objet `FormData` qui est sur le point d'êtresoumis// `action` est l'URL vers laquelle le formulaire pointe// exécuter`cancel()`vaempêcherlasoumission// `submitter` est l'élément`HTMLElement`quiaprovoqué lasoumissionduformulairereturnasync({result,update})=>{// `result` est un objet `ActionResult`// `update` est une fonction qui déclenchelalogiquequiaurait été exécutéepardéfautsice// callback n'avait pas été défini};}}>
Vous pouvez utiliser ces fonctions pour afficher et cacher des éléments d’interface de chargement,
entre autres.
Si vous renvoyez un callback, vous écrasez le comportement post-soumission par défaut. Pour le
récupérer, appelez update, qui accepte les paramètres invalidateAll et reset, ou utilisez
applyAction sur le résultat :
src/routes/login/+page
<script>import{enhance,applyAction}from'$app/forms';/**@type{import('./$types').PageProps}*/let{form}=$props();</script><formmethod="POST"use:enhance={({formElement,formData,action,cancel})=>{returnasync({result})=>{// `result` est un objet `ActionResult`if(result.type==='redirect'){goto(result.location);}else{awaitapplyAction(result);}};}}>
<scriptlang="ts">import{enhance,applyAction}from'$app/forms';importtype{PageProps}from'./$types';let{form}:PageProps=$props();</script><formmethod="POST"use:enhance={({formElement,formData,action,cancel})=>{returnasync({result})=>{// `result` est un objet `ActionResult`if(result.type==='redirect'){goto(result.location);}else{awaitapplyAction(result);}};}}>
Le comportement de applyAction(result) dépend de result.type :
success, failure — définit page.status en tant que result.status et met à jour form et
page.form en tant que result.data (indépendamment de la source de soumission, à la différence du
update venant de enhance)
Nous pouvons également implémenter de l’amélioration progressive nous-même, sans use:enhance, avec
un gestionnaire d’évènement normal sur l’élément <form> :
src/routes/login/+page
<script>import{invalidateAll,goto}from'$app/navigation';import{applyAction,deserialize}from'$app/forms';/**@type{import('./$types').PageProps}*/let{form}=$props();/**@param{SubmitEvent&{currentTarget:EventTarget&HTMLFormElement}}event*/asyncfunctionhandleSubmit(event){event.preventDefault();constdata=newFormData(event.currentTarget,event.submitter);constresponse=awaitfetch(event.currentTarget.action,{method:'POST',body:data});/**@type{import('@sveltejs/kit').ActionResult}*/constresult=deserialize(awaitresponse.text());if(result.type==='success'){// ré-exécute toutes les fonctions `load`, en cas de succèsawaitinvalidateAll();}applyAction(result);}</script><formmethod="POST"onsubmit={handleSubmit}><!-- contenu --></form>
<scriptlang="ts">import{invalidateAll,goto}from'$app/navigation';import{applyAction,deserialize}from'$app/forms';importtype{PageProps}from'./$types';importtype{ActionResult}from'@sveltejs/kit';let{form}:PageProps=$props();asyncfunctionhandleSubmit(event:SubmitEvent&{currentTarget:EventTarget&HTMLFormElement}){event.preventDefault();constdata=newFormData(event.currentTarget,event.submitter);constresponse=awaitfetch(event.currentTarget.action,{method:'POST',body:data});constresult:ActionResult=deserialize(awaitresponse.text());if(result.type==='success'){// ré-exécute toutes les fonctions `load`, en cas de succèsawaitinvalidateAll();}applyAction(result);}</script><formmethod="POST"onsubmit={handleSubmit}><!-- contenu --></form>
Notez que vous avez besoin de deserialize la réponse avant de la traiter en utilisant la méthode
correspondante importée depuis $app/forms. JSON.parse() ne suffit pas car les actions de
formulaires — comme les fonctions load — supportent également le renvoi d’objets Date ou
BigInt.
Si vous avez un fichier +server.js associé à votre +page.server.js, les requêtes fetch vont y
être dirigées par défaut. Si vous souhaitez envoyer une requête POST à une action de
+page.server.js, utilisez l’en-tête personnalisée x-sveltekit-action :
A Headers object, an object literal, or an array of two-item arrays to set request's headers.
:{'x-sveltekit-action':'true'}});
Alternatives
Les actions de formulaire sont la méthode recommandée pour envoyer des données au serveur,
puisqu’elles peuvent être améliorées progressivement, mais vous pouvez également utiliser des
fichiers +server.js pour exposer (par exemple) une API JSON. Voici ce à quoi une
telle interaction pourrait ressembler :
src/routes/send-message/+page
<script>functionrerun(){fetch('/api/ci',{method:'POST'});}</script><buttononclick={rerun}>Relancer la CI</button>
<scriptlang="ts">functionrerun(){fetch('/api/ci',{method:'POST'});}</script><buttononclick={rerun}>Relancer la CI</button>
importtype{RequestHandler(alias)typeRequestHandler=(event:RequestEvent<Record<string,any>,string|null>)=>MaybePromise<Response>importRequestHandler}from'./$types';exportconstPOSTconstPOST:RequestHandler:RequestHandler(alias)typeRequestHandler=(event:RequestEvent<Record<string,any>,string|null>)=>MaybePromise<Response>importRequestHandler=()=>{ // faire quelque chose
};
GET vs POST
Comme nous venons de le voir, pour invoquer une action de formulaire, vous devez utiliser
method="POST".
Certains formulaires n’ont pas besoin d’utiliser POST pour envoyer des données au serveur — les
inputs de recherche par exemple. Pour ces cas-là, vous pouvez utiliser method="GET" (ou de manière
équivalente, aucune method), et SvelteKit va traiter ces requêtes comme si elles venaient
d’éléments <a>, utilisant le routeur client plutôt qu’une navigation impliquant le rechargement
complet de la page :