ReactJS节点和Axios:no' access-control-allow-allow-origin'标题存在于请求的资源上

发布于 2025-02-10 16:35:22 字数 1887 浏览 1 评论 0原文

我现在正在学习编程,所以请原谅我的任何错误,我将感谢任何提示。 我有一个托管在以下域中的API(“ api-myapp.com”),我正在尝试从我的Local主机上创建前端以发布表单(只有登录用户才能发送)使用Axios,但是请求需要很长时间才能完成,并且完成后返回以下错误(在请求的资源上不存在“访问控制 - 允许 - 原始”标头。) (NET :: ERR_FAILED 504),我尝试了一些我在互联网上找到的解决方案,但似乎都没有起作用,这是我的代码:

前端:

 try {
        const response = await axios.post('/alunos/', {
            nome,sobrenome,idade,sangue,varinha,patrono,house,sala,
        });
        toast.success('Cadastrado com sucesso');
        console.log(response);
    } catch (e) {
        console.log(e);
        const errors = get(e, 'response.data.errors', []);
        errors.map((error) => toast.error(error));
    }

当您登录

 try {
    const response = yield call(axios.post, '/tokens', payload);
    yield put(actions.loginSuccess({ ...response.data }));
    axios.defaults.headers.Authorization = `Bearer ${response.data.token}`;
    toast.success('Login realizado com sucesso!');
    payload.navigate('/dashboard');
}

后端时

class App {
  constructor() {
    this.app = express();
    this.middlewares();
    this.routes();
  }

  middlewares() {
    this.app.use(cors({ origin: '*' }));
    this.app.use(helmet({ crossOriginResourcePolicy: false }));
    this.app.use(express.urlencoded({ extended: true }));
    this.app.use(express.json());
    this.app.use('/images/', express.static(resolve(__dirname, '..', 'uploads', 'images')));
  }

  routes() {
    this.app.use('/', homeRoutes);
    this.app.use('/prof', profRoutes);
    this.app.use('/tokens', tokenRoutes);
    this.app.use('/alunos', alunoRoutes);
    this.app.use('/casas', casaRoutes);
    this.app.use('/provas', provaRoutes);
    this.app.use('/materias', materiaRoutes);
    this.app.use('/salas', salaRoutes);
    this.app.use('/fotosAlunos', fotoAlunoRoutes);
    this.app.use('/fotosProf', fotoProfRoutes);
  }
}

I'm learning programming now so forgive me for any mistakes, I'll be grateful for any tips.
I have an API that is hosted in the following domain ("api-myapp.com") and I'm trying from my localhost where I'm creating my front-end to post a form (which only logged in users can send) using axios , but the request takes a long time to complete and when it completes it returns the following error (No 'Access-Control-Allow-Origin' header is present on the requested resource.)
(net::ERR_FAILED 504), I've tried some solutions I found on the internet but none seem to have worked, this is my code:

FrontEnd:

 try {
        const response = await axios.post('/alunos/', {
            nome,sobrenome,idade,sangue,varinha,patrono,house,sala,
        });
        toast.success('Cadastrado com sucesso');
        console.log(response);
    } catch (e) {
        console.log(e);
        const errors = get(e, 'response.data.errors', []);
        errors.map((error) => toast.error(error));
    }

When you logged in

 try {
    const response = yield call(axios.post, '/tokens', payload);
    yield put(actions.loginSuccess({ ...response.data }));
    axios.defaults.headers.Authorization = `Bearer ${response.data.token}`;
    toast.success('Login realizado com sucesso!');
    payload.navigate('/dashboard');
}

BackEnd

class App {
  constructor() {
    this.app = express();
    this.middlewares();
    this.routes();
  }

  middlewares() {
    this.app.use(cors({ origin: '*' }));
    this.app.use(helmet({ crossOriginResourcePolicy: false }));
    this.app.use(express.urlencoded({ extended: true }));
    this.app.use(express.json());
    this.app.use('/images/', express.static(resolve(__dirname, '..', 'uploads', 'images')));
  }

  routes() {
    this.app.use('/', homeRoutes);
    this.app.use('/prof', profRoutes);
    this.app.use('/tokens', tokenRoutes);
    this.app.use('/alunos', alunoRoutes);
    this.app.use('/casas', casaRoutes);
    this.app.use('/provas', provaRoutes);
    this.app.use('/materias', materiaRoutes);
    this.app.use('/salas', salaRoutes);
    this.app.use('/fotosAlunos', fotoAlunoRoutes);
    this.app.use('/fotosProf', fotoProfRoutes);
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空心↖ 2025-02-17 16:35:23

您必须启用后端的CORS才能通过不同的端口请求。
对于您的情况,由于您使用了Express和CORS库,因此可以尝试使用此情况。

app.use(
  cors({
    credentials: true,
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    allowedHeaders: ['Content-Type', 'Authorization'],
    origin: ['http://localhost:3000', 'http://localhost:3030'], // whatever ports you used in frontend
  })
);

You have to enable CORS in backend to allow request through different ports.
For your case since you are using express and cors library, you can try this.

app.use(
  cors({
    credentials: true,
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    allowedHeaders: ['Content-Type', 'Authorization'],
    origin: ['http://localhost:3000', 'http://localhost:3030'], // whatever ports you used in frontend
  })
);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文