【发布时间】:2021-08-30 17:56:23
【问题描述】:
所以我的设置如下,我有一个在 localhost:3001 上运行的 react 前端和一个在 localhost:3000 上运行的 nextjs 后端。我在 /api/employee 有一个休息端点,我正在尝试使用以下代码从我的前端获取数据:
fetch(process.env.REACT_APP_API_URL + "/employee/")
.then((response) => {
if (response.status === 200) {
return response.json();
} else {
throw new Error(response.statusText);
}
})
.then(
(result) => {
setLoaded(true)
dispatch(addEmployee(result));
}
)
.catch((error) => {
setLoaded(true)
setError("It looks like an Error happend when trying to load the data please reloade the Website and if the Problem persists notify the Administrator.")
setHasError(true)
})
但每次我尝试获取数据时都会出现 cors 错误:
Access to fetch at 'http://localhost:3000/api/employee/' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我尝试以多种不同的方式在我的后端启用 cors,但都没有奏效。 我尝试手动添加标题:
res.setHeader('Allow', ['GET', 'PUT'])
res.setHeader('Access-Control-Allow-Origin', '*')
我尝试使用 NextCors 包:
await NextCors(req, res, {
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
origin: '*',
optionsSuccessStatus: 200,
});
如果没有 cors 配置,我在 extjs 中的文件如下所示:
文件:pages/api/employee
export default async function handler(req, res) {
// i tried to configure cors here
if (req.method === 'PUT') {
const feed = await prisma.employee.create({
data: req.employee,
})
res.status(200).json(feed)
} else if (req.method === 'GET') {
const feed = await prisma.employee.findMany({});
res.status(200).json(feed)
}
else {
res.status(404)
}
}
所以我的问题是我需要做些什么才能正确配置 cors 以使用我的设置。
【问题讨论】: