Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在Next.Js中使用useffect进行网络调用时出现CORS错误_Reactjs_Cors_Next.js - Fatal编程技术网

Reactjs 在Next.Js中使用useffect进行网络调用时出现CORS错误

Reactjs 在Next.Js中使用useffect进行网络调用时出现CORS错误,reactjs,cors,next.js,Reactjs,Cors,Next.js,在getStaticProps中对superhero.com的API进行了网络调用,但当我尝试在useffect中进行相同调用时,抛出了CORS错误 在'https://superheroapi.com/api//1“起源”http://localhost:3000'已被CORS策略阻止:请求的资源上不存在'Access Control Allow Origin'标头。如果不透明响应满足您的需要,请将请求的模式设置为“no cors”,以获取禁用cors的资源 我曾尝试使用fetch和axios

getStaticProps
中对
superhero.com
的API进行了网络调用,但当我尝试在
useffect
中进行相同调用时,抛出了CORS错误

在'https://superheroapi.com/api//1“起源”http://localhost:3000'已被CORS策略阻止:请求的资源上不存在'Access Control Allow Origin'标头。如果不透明响应满足您的需要,请将请求的模式设置为“no cors”,以获取禁用cors的资源

我曾尝试使用fetch和axios进行网络呼叫,但都出现了相同的错误。Next.js是否存在问题或限制


编辑:尝试在
useffect
中使用JSON占位符API,它正在工作。
useffect
中的代码在前端/浏览器中运行,因此必须遵守CORS
getStaticProps
在构建时运行,因此没有CORS限制

如果superheroapi.com API在您的控制之下,您应该添加CORS响应头来修复该问题。否则,您需要创建反向代理,例如,

CORS 当您试图从一个域访问另一个域上的资源时,会发生CORS错误。它只在浏览器中发生,是一种安全功能

因此,本质上,当您从
https://superheroapi.com/api/1
localhost:3000
上时,浏览器首先询问
superheroapi.com
,“嘿,这个域能从你那里获取数据吗?”
superheroapi.com
会说,“我只接受来自这些域的请求”。如果
localhost:3000
不在该列表中,您将得到一个CORS错误

您可以通过
Access Control Allow Origin
标题更改
superheroapi.com
接受的域。您可以手动完成,或者在Next.js中有一个方便的npm包为您解决这个问题

在Next.js中修复CORS 默认情况下,在Next.js中,CORS头仅限于相同的域流量。但是,您可以更改此设置

实际上,Next.js在他们的文档中有一个关于向api路由添加CORS头的指南

不过,简而言之,首先安装CORS包

npm i cors
# or
yarn add cors
# or
pnpm add cors
然后将其添加到API路由

import Cors from 'cors'

// Initializing the cors middleware
const cors = Cors({
  methods: ['GET', 'HEAD'],
})

// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req, res, fn) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result) => {
      if (result instanceof Error) {
        return reject(result)
      }

      return resolve(result)
    })
  })
}

async function handler(req, res) {
  // Run the middleware
  await runMiddleware(req, res, cors)

  // Rest of the API logic
  res.json({ message: 'Hello Everyone!' })
}

export default handler

代码片段取自Next.js文档。所有的功劳都归于Next.js的制造商。

您必须在经过验证的域上运行代码。 某些api为本地主机请求提供cors错误

简单的方法是:尝试定义一个本地域(在主机文件中将该域的本地dns更改为127.0.0.1),然后像这样编写一个server.js文件。 将“next.yourdomain.com”替换为您的域;)

const{createServer,}=require('http');
const{parse,}=require('url');
const next=需要(“next”);
//const dev=process.env.NODE_env!='生产",;
const-dev=false;
const app=next({dev,});
const handle=app.getRequestHandler();
const HOST='next.yourdomain.com';
常数端口=8090;
app.prepare()然后(()=>{
createServer((请求、恢复)=>{
//确保将'true'作为第二个参数传递给'url.parse'。
//这告诉它解析URL的查询部分。
const parsedUrl=parse(req.url,true);
句柄(req、res、parsedUrl);
}).侦听(端口、主机,(错误)=>{
如果(错误)抛出错误;
log(`Starting Next.js at http://${HOST}:${PORT}`);
});
});
然后跑

next build&&node server.js


您还必须在最终部署时放弃此文件。

请参阅编辑。解决CORS错误的解决方案是什么?请参见上面的编辑。这是否回答了您的问题?这是一个非常合理的错误,与Next.js没有任何关系,我没有想到会发生这种错误,而是一时冲动将其发布在这里@答案中的engineforce非常简洁地解释了这一点。