Nuxt3 处理 API 路由中的饼干 🍪

huangapple go评论69阅读模式
英文:

Nuxt3 Handling Cookies in API Routes

问题

我有全局中间件:

import { useStore } from "~/store/useStore";

export default defineNuxtRouteMiddleware(async () => {
    await useFetch('/api/setCookie')
    await useFetch('/api/getCookie')
});

还有server/api/getCookie.ts文件中的这两个路由:

import { getCookie } from "h3";

export default defineEventHandler((event) => {

    const cookie = getCookie(event, 'test_cookie')

    console.log('get cookie in Event Handler', cookie)

    return {
        hello: getCookie(event, 'test_cookie')
    }
})

以及server/api/setCookie.ts

import { setCookie } from "h3";

export default defineEventHandler((event) => {

    console.log('set cookie in Event Handler')
    setCookie(event, 'test_cookie', 'test_value')

    return {
        hello: 'world'
    }
})

当我运行这个应用程序时,我希望创建Cookie并将其记录到控制台,但即使多次重新加载应用程序,它也不会保存Cookie。为什么?

英文:

I have global middleware:

import {useStore} from "~/store/useStore";

export default defineNuxtRouteMiddleware(async () => {
    await useFetch('/api/setCookie')
    await useFetch('/api/getCookie')
});

And those two routes in server/api/getCookie.ts file:

import { getCookie } from "h3";

export default defineEventHandler((event) => {

    const cookie = getCookie(event, 'test_cookie')

    console.log('get cookie in Event Handler', cookie)

    return {
        hello: getCookie(event, 'test_cookie')
    }
})

and server/api/setCookie.ts:

import { setCookie } from "h3";

export default defineEventHandler((event) => {

    console.log('set cookie in Event Handler')
    setCookie(event, 'test_cookie', 'test_value')

    return {
        hello: 'world'
    }
})

When I run this app I expect to create cookie and console.log it but it doesn't save cookie even on multiple reloads of the app:

Nuxt3 处理 API 路由中的饼干 🍪

Why?

答案1

得分: 1

我注意到你的服务器API上有一个错误,那就是你没有设置正在创建的API路由的类型。为了使setCookie起作用,路由的文件名必须以.post为后缀。

如果你想确保cookie能够到达你的getCookieAPI路由,创建一个服务器中间件,例如:

以下是与示例给定的工作代码:

~/server/middleware/get-cookie.ts

export default defineEventHandler((event) => {
    event.context.custom_cookie = getCookie(event, 'my_cookie');
});

Set Cookie路由
~/server/api/set-cookie.post.ts

export default defineEventHandler((event) => {
    try {
        setCookie(event, 'my_cookie', 'hello-my-cookie-12345', {
            httpOnly: true,
            secure: true,
            sameSite: 'none',
        });
        return 200;
    } catch (error) {
        return createError({
            statusCode: 500,
            statusMessage: 'Something went wrong.',
        });
    }
});

Get Cookie路由 ~/server/api/get-cookie.ts

export default defineEventHandler((event) => {
    try {
        console.log('Cookie is', event.context.custom_cookie);
        return 200;
    } catch (error) {
        return createError({ statusCode: 500, statusMessage: 'Something went wrong.' });
    }
})

event.context.custom_cookie 来自服务器中间件。

在你的中间件目录
~/middleware/cookie.ts

export default defineNuxtRouteMiddleware(async () => {
    await useFetch('/api/set-cookie', { method: 'POST' });
    await useFetch('/api/get-cookie');
});

在你的页面中定义中间件。

<script lang="ts" setup>
definePageMeta({
    middleware: 'cookie',
});
</script>
<template>
    <div>
        Hello World
    </div>
</template>
<style scoped lang="css"></style>

已测试并且可行。
Nuxt3 处理 API 路由中的饼干 🍪

https://www.youtube.com/watch?v=wAQWt1CdafE

英文:

One mistake I noticed on your sever API is that you did not set up what type of API route you are creating. In order to make the setCookie work, the file name of the route must be suffixed by .post.

If you want to make sure that the cookie will reach to your getCookie API route, create a server middleware. e.g

Here are the working codes in refferrence to the example given

~/server/middleware/get-cookie.ts

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

export default defineEventHandler((event) =&gt; {
    event.context.custom_cookie = getCookie(event, &#39;my_cookie&#39;);
});

<!-- end snippet -->

Set Cookie route
~/server/api/set-cookie.post.ts

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

export default defineEventHandler((event) =&gt; {
    try {
        setCookie(event, &#39;my_cookie&#39;, &#39;hello-my-cookie-12345&#39;, {
            httpOnly: true,
            secure: true,
            sameSite: &#39;none&#39;,
        });
        return 200
    } catch (error) {
        return createError({
            statusCode: 500,
            statusMessage: &#39;Something went wrong.&#39;,
        })
    }
});

<!-- end snippet -->

Get Cookie route ~/server/api/get-cookie.ts

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

export default defineEventHandler((event) =&gt; {
    try {
        console.log(&#39;Cookie is&#39;, event.context.custom_cookie)
        return 200
    } catch (error) {
        return createError({ statusCode: 500, statusMessage: &#39;Something went wrong.&#39; })
    }
})

<!-- end snippet -->

The event.context.custom_cookie is from the server middleware.

In your directory middleware
~/middleware/cookie.ts

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

export default defineNuxtRouteMiddleware(async () =&gt; {
    await useFetch(&#39;/api/set-cookie&#39;, { method: &#39;POST&#39; })
    await useFetch(&#39;/api/get-cookie&#39;)
});

<!-- end snippet -->

Define the middleware in your page.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

&lt;script lang=&quot;ts&quot; setup&gt;
definePageMeta({
    middleware: &#39;cookie&#39;,
});
&lt;/script&gt;
&lt;template&gt;
    &lt;div&gt;
        Hello World
    &lt;/div&gt;
&lt;/template&gt;
&lt;style scoped lang=&quot;css&quot;&gt;&lt;/style&gt;

<!-- end snippet -->

Tested and it works
Nuxt3 处理 API 路由中的饼干 🍪

https://www.youtube.com/watch?v=wAQWt1CdafE

huangapple
  • 本文由 发表于 2023年7月17日 11:15:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定