sveltejs / realworld

SvelteKit implementation of the RealWorld app
https://realworld.svelte.dev
MIT License
2.24k stars 353 forks source link

Sending query parameter via SvelteKit form action #182

Closed alokmahor closed 2 weeks ago

alokmahor commented 3 weeks ago

I have created a website using SvelteKit. I am using form action for handling login form.

src/routes/(beforeAuth)/login/+page.svelte have login form

<form use:enhance method="post" action="/login?/login">

    <label>Username:</lable>
    <input type="text" name="username" />

    <label>Password:</lable>
    <input type="password" name="password" />

    <Button text="Sign In" type="submit" />
<form>

src/routes/(beforeAuth)/login/+page.server.js have login action

export const actions = {
    login: async ({ cookies, request }) => {
        const data = await request.formData();
        let body
            try{
                 body = await api.post("account/login/", {
                    username: data.get('username'),
                    password: data.get('password')
            });
            }catch(err) {
                return {
                    message: "username or password is not vailid",
                    login: false
                }
            }

        if (body.status === 401) {
            return fail(401, { tryAgain: true })

        }
        if(body.status == 400) {
            return {
                message: body.data.message,
                login: false
            }
        }

        if(body.status == 200) {
            const value = btoa(JSON.stringify(body));
            cookies.set('jwt', value, { secure: false, path: '/', maxAge:60 * 60 * 6 });
            redirect(307, '/my-profile')

        } else {
            return {
                message: "username or password is not vailid",
                login: false
            }
        }
    },
    logout: async ({ cookies, locals }) => {
        cookies.delete('jwt', {path:'/'});
        locals.user = null;
    },
};

This login form and action is woring fine. But now I want to send query parameter via form action. So I tried set action to /login?/login?redirect=some-path

e.g.

<form use:enhance method="post" action="/login?/login?redirect=some-path">

This is giving me error

SvelteKitError: No action with name 'login?redirect' found

What is right way to send query parameter via form action in SvelteKit?

alokmahor commented 2 weeks ago

/login?/login&redirect=some-path is correct format