Request is presenting Cross-Origin Request Blocked in Reactjs app

Asked

Viewed 1,924 times

1

I am developing an application in React and previously created a restful API with Node and express, in my api I added the module Cors const cors = require('cors'); and added it at the boot of the same so that the requests are allowed, until then all right, the problem and when I pass to the application React, where I also added the module Next const axios = require("axios"); to handle the requests made by the application and thus avoid Cross-Origin but even so it returns me the lock of the same. When I make a query in another API the application can bring me the data, I do not know if the reason and because the two are running on the same machine.

From now on I appreciate the attention of all who can help me! :)

Excerpt Reactjs

 axios.get("http://localhost:3001/api/MarcodeContainers").then(function (resposta) {

        var teste = resposta.data;

        console.log(teste);

    });

Excerpt From express startup nodejs

const http = require('http');
const express = require('express');
const morgan = require('morgan');
const webServerConfig = require('../config/web-server.js');
const router = require('./router');
const cors = require('cors');

let httpServer;
function initialize() {
  return new Promise((resolve, reject) => {
    const app = express();
    app.use(cors());

    httpServer = http.createServer(app);

    app.use(morgan('combined'));
    app.use(express.json({
        reviver: reviveJson
    }));

    app.use('/api', router);

    httpServer.listen(webServerConfig.port)
        .on('listening', () => {
            console.log(`Web server ouvindo em localhost:${webServerConfig.port}`);

            resolve();
        })
        .on('error', err => {
            reject(err);
        });
});
}
  • 1

    Add crossdomain: true in Xios. Ex axios.get("http://localhost:3001/api/MarcodeContainers", {crossdomain: true});

  • Thank you for the reply Justcase, but unfortunately it did not work!

  • What you have in the file router?

1 answer

0

Thank you all with your answers, but apparently I managed to find the solution, in a question here in the stack. follows the link Requisition with Axios

"proxy":"http://localhost:3001/api",

I added the above line of code in my package.json and it worked correctly ,performed the request without presenting the CROS message. I hope it continues like this after performing some module update.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.