英文:
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:
Why?
答案1
得分: 1
我注意到你的服务器API上有一个错误,那就是你没有设置正在创建的API路由的类型。为了使setCookie
起作用,路由的文件名必须以.post
为后缀。
如果你想确保cookie能够到达你的getCookie
API路由,创建一个服务器中间件,例如:
以下是与示例给定的工作代码:
~/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>
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) => {
event.context.custom_cookie = getCookie(event, 'my_cookie');
});
<!-- 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) => {
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.',
})
}
});
<!-- 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) => {
try {
console.log('Cookie is', event.context.custom_cookie)
return 200
} catch (error) {
return createError({ statusCode: 500, statusMessage: 'Something went wrong.' })
}
})
<!-- 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 () => {
await useFetch('/api/set-cookie', { method: 'POST' })
await useFetch('/api/get-cookie')
});
<!-- end snippet -->
Define the middleware in your page.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
<script lang="ts" setup>
definePageMeta({
middleware: 'cookie',
});
</script>
<template>
<div>
Hello World
</div>
</template>
<style scoped lang="css"></style>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论