按照官方的Next js文档,我可以使用中间件在服务器端获得cookie.

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
export function middleware(request: NextRequest) {
  // Assume a "Cookie:nextjs=fast" header to be present on the incoming request
  // Getting cookies from the request using the `RequestCookies` API
  let cookie = request.cookies.get('nextjs')
  console.log(cookie) // => { name: 'nextjs', value: 'fast', Path: '/' }
  const allCookies = request.cookies.getAll()
  console.log(allCookies) // => [{ name: 'nextjs', value: 'fast' }]
 
  request.cookies.has('nextjs') // => true
  request.cookies.delete('nextjs')
  request.cookies.has('nextjs') // => false
 
 
}

我如何保存我的cookie在服务器端,然后使用cookie在服务器组件

推荐答案

cookies种功能:

很高兴知道:.Set()仅在服务器操作或路由中可用 操控者.

这是Cookies函数:

function cookies() {
    if ((0, _staticgenerationbailout.staticGenerationBailout)("cookies", {
        link: "https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering"
    })) {
        return _requestcookies.RequestCookiesAdapter.seal(new _cookies.RequestCookies(new Headers({})));
    }
    const requestStore = _requestasyncstorage.requestAsyncStorage.getStore();
    if (!requestStore) {
        throw new Error("Invariant: cookies() expects to have requestAsyncStorage, none available.");
    }
    const asyncActionStore = _actionasyncstorage.actionAsyncStorage.getStore();
    if (asyncActionStore && (asyncActionStore.isAction || asyncActionStore.isAppRoute)) {
        // We can't conditionally return different types here based on the context.
        // To avoid confusion, we always return the readonly type here.
        return requestStore.mutableCookies;
    }
    return requestStore.cookies;
}`

requestStore.cookiesRequestCookies个类实例,即:

declare class RequestCookies {
    constructor(requestHeaders: Headers);
    [Symbol.iterator](): IterableIterator<[string, RequestCookie]>;
    /**
     * The amount of cookies received from the client
     */
    get size(): number;
    get(...args: [name: string] | [RequestCookie]): RequestCookie | undefined;
    getAll(...args: [name: string] | [RequestCookie] | []): RequestCookie[];
    has(name: string): boolean;
    set(...args: [key: string, value: string] | [options: RequestCookie]): this;
    /**
     * Delete the cookies matching the passed name or names in the request.
     */
    delete(
    /** Name or names of the cookies to be deleted  */
    names: string | string[]): boolean | boolean[];
    /**
     * Delete all the cookies in the cookies in the request.
     */
    clear(): this;
    toString(): string;
}

    

如果您想将其设置为中间件,

response.cookies.set(({
       name:"foo",
       value:"bar",
       path:"/"
}))

Javascript相关问答推荐

如何使用React渲染器放置根dis?

脚本.js:3:20未捕获的类型错误:无法读取空的属性(读取addEventHandler)

如何访问react路由v6加载器函数中的查询参数/搜索参数

主要内部的ExtJS多个子应用程序

序列查找器功能应用默认值而不是读取响应

React:未调用useState变量在调试器的事件处理程序中不可用

如何最好地从TypScript中的enum获取值

我应该在redux reducer中调用其他reducer函数吗?

硬币兑换运行超时

Snowflake JavaScript存储过程返回成功,尽管预期失败

为什么ngModel不能在最后一个版本的Angular 17上工作?'

我们如何从一个行动中分派行动

我的角模板订阅后不刷新'

TinyMCE 6导致Data:Image对象通过提供的脚本过度上载

MarkLogic-earch.suggest不返回任何值

打字脚本中方括号符号属性访问和拾取实用程序的区别

在Odoo中如何以编程方式在POS中添加产品

对具有相似属性的对象数组进行分组,并使用串连的值获得结果

不协调嵌入图片

MongoDB通过数字或字符串过滤列表