Caio Severino
Caio Severino

Reputation: 13

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

Upvotes: 0

Views: 3585

Answers (1)

Yuki Lee
Yuki Lee

Reputation: 116

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

Upvotes: 2

Related Questions