首页 > 解决方案 > NextJS - fetch() 仅在 getServerSideProps() 内有效

问题描述

我用于发出 api 请求的 fetch() 方法仅在 getServerSideProps() 方法中有效。

例如,我有 api 调用来获取客户购物车(它在 getServerSideProps 内):

    const res = await fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer ' + jwtToken
      }
    });

它工作正常,我得到了来自客户购物车的 api 的响应。但是,当我尝试在单击按钮时进行该 api 调用,并且当我移动该内部按钮单击句柄方法时,我首先得到:

CORS 策略已阻止从源“http://localhost:3000”获取“...”的访问权限:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头存在于请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

之后,当我将模式设置为“no-cors”时,我得到了这个:

GET ... net::ERR_ABORTED 400(错误请求)

那么,当在 getServerSideProps 内部时,怎么可能没有任何 CORS 问题并且一切都很好,但是当单击按钮时,我会遇到 CORS 问题,然后出现其他“错误请求”问题。

标签: next.jsfetchfetch-api

解决方案


因为当 API 响应没有Access-Control-Allow-Headers时,浏览器会阻止 API 请求。但是,当您在 getServerSideProps 中获取 API 时,API 请求是由 Node.js 服务器发出的,它不检查 Access-Control-Allow-Headers。

如果你想在浏览器中发出这个 API 请求,那么你可以通过以下方式修复它:

// If you can change the API code, here's an example to add the CORS headers in a netlify serverless function, this is the API response that I return from a serverless function 
   return {
      statusCode: 200,
      headers: {
        /* Required for CORS support to work */
        'Access-Control-Allow-Origin': '*', // you can add the domain names here or '*' will allow all domains
        /* Required for cookies, authorization headers with HTTPS */
        'Access-Control-Allow-Credentials': true
      },
      body: JSON.stringify({
        message: 'Hello from netlify'
      })
    }

或者如果您的 API 后端位于 Node.js 和 Express.js 中,您可以使用cors npm 包

如果您无权更改 API,请尝试编写一个包装 API(或者您可以说是代理 API),该 API 将发出 API 请求并将其响应发送给您。

或者,如果您只希望 API 请求仅发生一次(在页面加载时,如 componentDidMount),您可以使用 getServerSideProps。

有关如何修复 CORS 错误的更详细说明,请阅读 Access-Control-Allow-Origin 标头如何工作?


推荐阅读