首页 > 解决方案 > 无法在 Next.js 中通过 CORS 处理 DELETE 请求

问题描述

添加后...

async headers() {
        return [
            {
            source: "/api/:path*",
            headers: [
                { key: "Access-Control-Allow-Credentials", value: "true" },
                { key: "Access-Control-Allow-Origin", value: "*" },
                { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
                { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
            ]}
        ]
    }

next.config.js我可以通过 CORS 处理和GET处理POST,但不能处理DELETE. 它甚至没有到达我的处理程序,所以这里讨论的中间件解决方案没有帮助。

这是我的 api 处理程序:

import { makeUserSupabase } from '../../../../../../../../lib/initSupabase'
import Cors from 'cors'

// I added this per https://nextjs.org/docs/api-routes/api-middlewares but it makes no difference because my request is not even reaching the handler 
const cors = Cors({
  methods: ['GET', 'HEAD','DELETE'],
})

// 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, res, fn) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result) => {
      if (result instanceof Error) {
        return reject(result)
      }

      return resolve(result)
    })
  })
}

async function deleteSavedTemplate(req, res) {

  /* Code */
    
}

const main = async (req, res) => {

  await runMiddleware(req, res, cors)

  console.log('we have arrived')  
  if (req.method === 'DELETE') {
    return await deleteSavedTemplate(req, res)
  } else {
    return res.status(405).end();
  }

}

export default main

正在从这里调用 API:

const url = `${apiServer}/v1/users/me/templates/popular/saves/${template.id}`
            await fetch(url, {
                headers: headers,
                method: 'DELETE'              
            })

${apiServer}我们的http://localhost:8000域名在哪里

请注意,对DELETE请求的响应包括: Access-Control-Allow-Methods: OPTIONS, GET

如何DELETE通过 CORS 启用?

更新

我现在认为问题出在配置中,并且重定向或重写都没有拾取标题。

module.exports = {
  async redirects() {
       return [
          {
            source: '/api/:dest*',
            destination: '/:dest*',
            permanent: true,
          }
      ]
    },  
    async rewrites() {
      return [
          {
            source: "/v1/:dest*",
            destination: "/api/v1/:dest*",         
        },
        {
            source: "/v0/:dest*",
            destination: "/api/v0/:dest*",        
        }
      ]
    },
  async headers() {
    return [
      {
        // matching all API routes
        source: "/api/:dest*",
        headers: [
          { key: "Access-Control-Allow-Credentials", value: "true" },
          { key: "Access-Control-Allow-Origin", value: "*" },
          { key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
          { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
        ]
      }
    ]
  }
};

标签: corsnext.js

解决方案


推荐阅读