Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

464
Vistas
ReactJS Node and Axios :No 'Access-Control-Allow-Origin' header is present on the requested resource

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);
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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
  })
);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda