javascript - 无法使用 nextJs 从外部 api 获取数据 (ERR_ABORTED 400)
问题描述
我正在尝试使用 NextJS 从外部 API 获取一些数据。我已经用邮递员测试了 API url,它工作正常 - 结果被正确获取。但是当我尝试使用fetch()
NextJS 中的方法获取 API 数据时,它会net::ERR_ABORTED 400
在浏览器控制台中出现错误。
这是一段代码:
反应组件:
import {fetchApiProduct} from "../../../lib/content-api";
export default function ProductPage(params) {
const product = fetchApiProduct();
return (
<>
<h3>product.name</h3>
</>
);
}
fetachApiProduct()
方法:
export async function fetchApiProduct() {
const sku = await useRouter().query.sku;
const url = `https://sometesturl/api/product/${sku}`;
console.log(url);
const res = await fetch(url, {
method: 'GET',
mode: 'no-cors',
headers: {
'Accept': 'application/json'
}
})
console.log(res);
return res;
}
编辑:
如果我只使用:
await fetch(url);
然后这就是我在控制台中得到的:
- CORS 策略已阻止从源“http://localhost:3000”获取“...”的访问权限:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
- 净::ERR_FAILED
- Uncaught (in promise) TypeError: Failed to fetch