注册免广告
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
×
 
 本帖最后由 HelloWorld 于 2025-3-16 08:54 编辑  
 
参考官方文档:https://github.com/vercel/next.j ... s/pages/api/cors.ts- import type { NextApiRequest, NextApiResponse } from 'next'
 
 - import Cors from 'cors'
 
  
- // Initializing the cors middleware
 
 - // You can read more about the available options here: https://github.com/expressjs/cors#configuration-options
 
 - const cors = Cors({
 
 -   methods: ['POST', 'GET', 'HEAD'],
 
 - })
 
  
- // Helper method to wait for a middleware to execute before continuing
 
 - // And to throw an error when an error happens in a middleware
 
 - function runMiddleware(
 
 -   req: NextApiRequest,
 
 -   res: NextApiResponse,
 
 -   fn: Function
 
 - ) {
 
 -   return new Promise((resolve, reject) => {
 
 -     fn(req, res, (result: any) => {
 
 -       if (result instanceof Error) {
 
 -         return reject(result)
 
 -       }
 
  
-       return resolve(result)
 
 -     })
 
 -   })
 
 - }
 
  
- export default async function handler(
 
 -   req: NextApiRequest,
 
 -   res: NextApiResponse
 
 - ) {
 
 -   // Run the middleware
 
 -   await runMiddleware(req, res, cors)
 
  
-   // Rest of the API logic
 
 -   res.json({ message: 'Hello Everyone!' })
 
 - }
 
  复制代码 |