使用MongoDB API在Vercel上部署Next.js 13应用程序时的CORS问题

trnvg8h3  于 8个月前  发布在  Go
关注(0)|答案(1)|浏览(94)

我在Vercel上部署我的Next.js 13应用程序时遇到了CORS问题,特别是在与基于MongoDB的API交互时。API包括基本的CRUD操作,我当前的获取配置如下:

// individual PUT/DELETE/GET

const res = await fetch(`http://localhost:3000/api/topics/${id}`, {
  cache: 'no-store',
});

// generic GET/POST

const res = await fetch(`http://localhost:3000/api/topics/`, {
  cache: 'no-store',
});

字符串
我怀疑CORS问题可能与API端点有关,我想知道在部署到Vercel时是否需要修改它。是否有人可以澄清此端点是否正确或是否需要调整?
此外,我尝试通过在next.js.js文件中配置Next.js头文件来解决CORS问题,如下所示:

/** @type {import('next').NextConfig} */
const nextConfig = {
  async headers() {
    return [
      {
        source: '/api/:path*',
        headers: [
          { key: 'Access-Control-Allow-Credentials', value: 'true' },
          { key: 'Access-Control-Allow-Origin', value: 'http://localhost:3000/api/topics' },
          { key: 'Access-Control-Allow-Methods', value: 'GET, DELETE, PATCH, 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' },
        ],
      },
    ];
  },
};

module.exports = nextConfig;


尽管有这些配置,CORS问题仍然存在。有人能提供解决这个CORS问题的指导吗?
文件夹结构:
/app/API/topics/route.ts -通用路由/app/API/topics/[id]/route.ts -单个路由

另外,考虑到部署在Vercel上,我的fetch配置中指向http://localhost:3000是正确的,还是应该根据部署的环境修改?

ih99xse1

ih99xse11#

所以我通过添加一个env变量来存储正确的URL来解决这个问题

NEXT_PUBLIC_BASE_API_URL=http://localhost:3000

字符串
并将其添加到每一个fetch,如下面的行

const rest = await fetch(`${BASE_API_URL}/api/topics`, {
      cache: 'no-store',
    });


但由于我将把它部署到Vercel,所以在应用程序部署之前我没有在那里配置它,所以当部署完成时,我现在有了正确的URL,然后我在Vercel控制台中设置env变量,GETS开始工作。
仅在生产中,URL将是下一个URL(示例一)

NEXT_PUBLIC_BASE_API_URL=crud-next-git-main.vercel.app


所以这是一件事删除本地主机,如果不是生产。
但我还是得到了CORS问题,所以我更新下一个配置为:

const nextConfig = {
  async headers() {
    return [
      {
        // matching all API routes
        source: '/api/:path*',
        headers: [
          { key: 'Access-Control-Allow-Credentials', value: 'true' },
          { key: 'Access-Control-Allow-Origin', value: '*' },
          {
            key: 'Access-Control-Allow-Methods',
            value: 'GET,DELETE,PATCH,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',
          },
        ],
      },
    ];
  },
};

module.exports = nextConfig;


现在API工作正常,没有任何Cors问题。我参考了这篇URL文章,它帮助我理解了发生了什么。https://blog.logrocket.com/using-cors-next-js-handle-cross-origin-requests/

相关问题