Heim > Fragen und Antworten > Hauptteil
Bei der Verwendung von Express habe ich Benutzer wie request.user
:
import jwt from "jsonwebtoken"; import asyncHandler from "express-async-handler"; import User from "../models/userModel.js"; const protect = asyncHandler(async (req, res, next) => { let token; token = req.cookies.jwt; if (token) { try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = await User.findById(decoded.userId).select("-password"); next(); } catch (error) { res.status(401); throw new Error("Not authorized , invalid token"); } } else { res.status(401); throw new Error("Not authorized , no token"); } }); export { protect }; And I was able to get the current user like this : const createPost = asyncHandler(async (req, res) => { const { content, image } = req.body; const user = req.user;
Aber wie macht man das mit NextJS 13 API-Routing und Middleware und wie verwendet man Cookies? Ich bin neu bei NextJS und wäre daher für jede Hilfe sehr dankbar.
P粉1769805222023-09-08 00:18:14
在 Next.js 中,您可以使用 NextRequest 和 NextResponse 上的 cookie 扩展来读取和操作 cookie。具体方法如下:
首先,您需要从 next/headers 导入 cookie:
import { cookies } from 'next/headers'
然后,你可以得到这样的cookie:
const cookieStore = cookies() const token = cookieStore.get('token')
要设置 cookie,您需要使用 Set-Cookie 标头返回一个新的响应:
return new Response('Hello, Next.js!', { status: 200, headers: { 'Set-Cookie': `token=${token}` }, })
您还可以使用 NextRequest 对象来读取 cookie:
export async function GET(request) { const token = request.cookies.get('token') }
对于传入的请求,cookie 具有以下方法:get、getAll、set 和 delete cookies。您可以使用 has 检查 cookie 是否存在,或使用clear 删除所有 cookie。
对于传出响应,cookie 具有以下方法 get、getAll、set 和 delete。
以下是如何使用这些方法的示例:
import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { 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 const response = NextResponse.next() response.cookies.set('vercel', 'fast') response.cookies.set({ name: 'vercel', value: 'fast', path: '/', }) cookie = response.cookies.get('vercel') console.log(cookie) // => { name: 'vercel', value: 'fast', Path: '/' } return response }