如何解决 CORS 标头“Access-Control-Allow-Origin”缺失的问题)。状态代码:在 nextjs 13 中使用 cloudinary 时为 502?

问题描述 投票:0回答:1

我的跨源请求被阻止:同源策略不允许读取 https://api.cloudinary.com/v1_1/codestacks/image/upload 处的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”丢失)。状态代码:使用 cloudinary 上传图像时,nextjs 13 中的 502。

我用过

const data = new FormData();
            data.append('file', image);
            data.append('upload_preset', 'CodeStacksProfileImages');
            data.append('cloud_name', 'codestacks');
            data.append('folder', 'CodeStacksProfileImages');

            let imageUrl;
            const uploadImagePromise = new Promise((resolve) => {
                const response = fetch('https://api.cloudinary.com/v1_1/codestacks/image/upload', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                    body: data,
                });
                resolve(response);
            });

但出现以下错误: 跨源请求被阻止:同源策略不允许读取 https://api.cloudinary.com/v1_1/codestacks/image/upload 处的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”丢失)。状态代码:502。

首先我使用的是axios,它运行良好,但是当我切换到fecth时,它给出了错误。

next.js13 cloudinary
1个回答
0
投票

如果您使用 axios,则需要使用 withCredentials,您可以在 App.js 文件中设置默认值。我的意思是你必须通过 withCredentials= true

将请求从前端发送到后端
 axios.defaults.withCredentials = true;

并在后端的 CORS_ORIGIN_WHITELIST 部分更改后端设置前端服务器中的设置文件

 CORS_ORIGIN_WHITELIST = [
    'https://ec2-ip/login',
   'http://127.0.0.1:3000',
    'your frontend local host url'
  ]
© www.soinside.com 2019 - 2024. All rights reserved.