完善异常跳转
This commit is contained in:
@@ -2,6 +2,7 @@
|
|||||||
import {API_BASE_URL, ApiResponse, CLIENT_ID, CLIENT_SECRET} from '@/lib/api'
|
import {API_BASE_URL, ApiResponse, CLIENT_ID, CLIENT_SECRET} from '@/lib/api'
|
||||||
import {add, isBefore} from 'date-fns'
|
import {add, isBefore} from 'date-fns'
|
||||||
import {cookies, headers} from 'next/headers'
|
import {cookies, headers} from 'next/headers'
|
||||||
|
import {redirect} from 'next/navigation'
|
||||||
import {cache} from 'react'
|
import {cache} from 'react'
|
||||||
|
|
||||||
export type TokenResp = {
|
export type TokenResp = {
|
||||||
@@ -106,7 +107,6 @@ const _callByUser = cache(async <R = undefined>(
|
|||||||
// ======================
|
// ======================
|
||||||
|
|
||||||
async function call<R = undefined>(url: string, body: RequestInit['body'], auth?: string): Promise<ApiResponse<R>> {
|
async function call<R = undefined>(url: string, body: RequestInit['body'], auth?: string): Promise<ApiResponse<R>> {
|
||||||
let response: Response
|
|
||||||
try {
|
try {
|
||||||
const reqHeaders = await headers()
|
const reqHeaders = await headers()
|
||||||
const reqIP = reqHeaders.get('x-forwarded-for')
|
const reqIP = reqHeaders.get('x-forwarded-for')
|
||||||
@@ -118,15 +118,14 @@ async function call<R = undefined>(url: string, body: RequestInit['body'], auth?
|
|||||||
if (reqIP) callHeaders['X-Forwarded-For'] = reqIP
|
if (reqIP) callHeaders['X-Forwarded-For'] = reqIP
|
||||||
if (reqUA) callHeaders['User-Agent'] = reqUA
|
if (reqUA) callHeaders['User-Agent'] = reqUA
|
||||||
|
|
||||||
response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: callHeaders,
|
headers: callHeaders,
|
||||||
body,
|
body,
|
||||||
})
|
})
|
||||||
}
|
|
||||||
catch (e) {
|
if (response.status === 401) {
|
||||||
console.error('后端请求失败', url, (e as Error).message)
|
return redirect('/login?redirect=' + encodeURIComponent(url.replace(API_BASE_URL, '')))
|
||||||
throw new Error(`请求失败,网络错误`)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const type = response.headers.get('Content-Type') ?? 'text/plain'
|
const type = response.headers.get('Content-Type') ?? 'text/plain'
|
||||||
@@ -167,6 +166,11 @@ async function call<R = undefined>(url: string, body: RequestInit['body'], auth?
|
|||||||
}
|
}
|
||||||
|
|
||||||
throw new Error(`无法解析响应数据,未处理的 Content-Type: ${type}`)
|
throw new Error(`无法解析响应数据,未处理的 Content-Type: ${type}`)
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
console.error('后端请求失败', url, (e as Error).message)
|
||||||
|
throw new Error(`请求失败,网络错误`)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 导出
|
// 导出
|
||||||
|
|||||||
Reference in New Issue
Block a user