在接下来的js中,auth with react查询

发布于 2025-02-03 08:39:33 字数 2813 浏览 4 评论 0原文

告诉我,我想制作中间件来保护管理员页面,我可以通过该项目的会议授权。该项目本身在下一步。我想使用React查询来保护页面,但是我会发现错误:发生了错误:意外的令牌<在位置0中的JSON中,React查询

API:

import type { NextApiRequest, NextApiResponse } from 'next'
import { route } from 'next/dist/server/router'
import { useRouter } from 'next/router'
import checkSession from '../../src/services/checkCookie'

export async function middleware(req: NextApiRequest,res:NextApiResponse) {
 if (req.method === 'GET') {
  try {
    const router= useRouter()
    const sid = req.cookies['sid']
    const admin = await checkSession(sid)
    console.log(router.pathname)
    // if (router.pathname === '/admin/login' || router.pathname === '/admin/regAdmin' || admin) {
    //     return res.next()
    // }
    res.send(admin)
    const host = process.env.NODE_ENV === 'production' ? process.env.HOST : 'http://localhost:3000'
    // return  res.redirect(host + '/admin/login')
    return  res.send({ redirectUrl: '/admin/login' })
  }catch (error) {
    console.error(error)
    res.status(500).send({ message: "Server error" })
  }
 }else{
    res.status(404).send({ message: "adress error" })
 }
}

API中的服务(checkSessin):

export default async function checkSession (token: string) {
    // const token = req.cookies['sid']
    if (typeof window === 'undefined' && token) {
        const unsign = (await import('./signature')).unsign
        const sessionToken = unsign(token, process.env.SECRET!)
        if (sessionToken && typeof sessionToken === 'string') {
            const db = (await import('../../prisma')).default
            const session = db.session.findUnique({ where: { sessionToken }, 
                include: { admin: true } })
            if (session) {
                return { admin: session.admin }
            }
        }
    }
}

页面管理员:

import { NextPage } from "next"
import AdminLayout from "../../src/component/admin/AdminLayout"
import { SalesAdminComponent } from "../../src/component/admin/SalesAdmin"
import { useQuery } from 'react-query'


const  AdminTable: NextPage = () => {

  const { isLoading, error, data,isSuccess} = useQuery('sid', () =>
   fetch('api/checkSession',{
    method:'GET',
    headers: {
      "Content-Type": "application/json"
    }
   }).then(res =>res.json())
  )
    if (isLoading) return 'Loading...'
    if (error) return 'An error has occurred: ' + error.message

    return (
      <>
       {isSuccess &&
        <AdminLayout title="OPEL Admin">
            <SalesAdminComponent />
        </AdminLayout>
       }
       {isLoading && <p>Loading..</p>}
       {error && <p>Error occurred!</p>}
      </>
    )
  }

  export default AdminTable

Tell me I want to make middleware to protect the administrator pages, I have authorization through sessions on the project. The project itself is on next js . I want to use React Query to protect pages, but I get the error: An error has occurred: Unexpected token < in JSON at position 0 react query

APi:

import type { NextApiRequest, NextApiResponse } from 'next'
import { route } from 'next/dist/server/router'
import { useRouter } from 'next/router'
import checkSession from '../../src/services/checkCookie'

export async function middleware(req: NextApiRequest,res:NextApiResponse) {
 if (req.method === 'GET') {
  try {
    const router= useRouter()
    const sid = req.cookies['sid']
    const admin = await checkSession(sid)
    console.log(router.pathname)
    // if (router.pathname === '/admin/login' || router.pathname === '/admin/regAdmin' || admin) {
    //     return res.next()
    // }
    res.send(admin)
    const host = process.env.NODE_ENV === 'production' ? process.env.HOST : 'http://localhost:3000'
    // return  res.redirect(host + '/admin/login')
    return  res.send({ redirectUrl: '/admin/login' })
  }catch (error) {
    console.error(error)
    res.status(500).send({ message: "Server error" })
  }
 }else{
    res.status(404).send({ message: "adress error" })
 }
}

Service in api (checkSessin) :

export default async function checkSession (token: string) {
    // const token = req.cookies['sid']
    if (typeof window === 'undefined' && token) {
        const unsign = (await import('./signature')).unsign
        const sessionToken = unsign(token, process.env.SECRET!)
        if (sessionToken && typeof sessionToken === 'string') {
            const db = (await import('../../prisma')).default
            const session = db.session.findUnique({ where: { sessionToken }, 
                include: { admin: true } })
            if (session) {
                return { admin: session.admin }
            }
        }
    }
}

page admin :

import { NextPage } from "next"
import AdminLayout from "../../src/component/admin/AdminLayout"
import { SalesAdminComponent } from "../../src/component/admin/SalesAdmin"
import { useQuery } from 'react-query'


const  AdminTable: NextPage = () => {

  const { isLoading, error, data,isSuccess} = useQuery('sid', () =>
   fetch('api/checkSession',{
    method:'GET',
    headers: {
      "Content-Type": "application/json"
    }
   }).then(res =>res.json())
  )
    if (isLoading) return 'Loading...'
    if (error) return 'An error has occurred: ' + error.message

    return (
      <>
       {isSuccess &&
        <AdminLayout title="OPEL Admin">
            <SalesAdminComponent />
        </AdminLayout>
       }
       {isLoading && <p>Loading..</p>}
       {error && <p>Error occurred!</p>}
      </>
    )
  }

  export default AdminTable

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心房敞 2025-02-10 08:39:33

这里发生了很多事情。响应可能是无法解释为JSON的HTML页面。请在服务器和浏览器中包括日志。

另外,您为什么使用服务器上的客户端路由器?

Lots of things are going on here. The response is probably an HTML page that cannot be parsed to JSON. Please include logs both from the server and the browser.

Also, why are you using the client router on the server?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文