cors - 无法在 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" },
]
}
]
}
};
解决方案
推荐阅读
- python-3.x - Pandas 多表提取
- mongodb - 如何等待副本赶上大师
- android-studio - 如何在另一个 recyclerview 中滚动 recyclerview onItemClick?
- adobe - 在哪里可以找到 adobe Dreamweaver 测验?
- java - 来自java的Amazon cognito未经身份验证的流
- docker - 使用 docker-compose 运行 Edgex-UI-GO
- eclipse - 插件片段看不到宿主插件中的包
- css - 小心!Object-fit:Cover 在最新的 Chrome 更新中不起作用,是错误还是他们放弃了支持?
- python - 即使在更改之后,Python 脚本语法错误
- python - 自定义虚线 matplotlib