next.js - 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 问题,然后出现其他“错误请求”问题。
解决方案
因为当 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 标头如何工作?
推荐阅读
- google-cloud-platform - 通过对话流代理从 Google Cloud Datastore 读取数据
- typescript - 如何让 jasmine.json 包含我的声明合并文件?
- python - 如何选择使用哪种字符编码?
- python - 编写一个程序,读取一个字符串并打印它是否
- excel - 细致入微的 Excel 问题;计算比例
- javascript - 通过javascript获取表单字段数据会抛出错误(值为null)
- reactjs - React ENV 和 axios url 获取
- php - 请求类的自定义验证规则不起作用 laravel 7
- php - 定义laravel关系时未找到列1054错误
- rust - 是否有推荐的模式来构建具有嵌套类型的 Flatbuffers?