Home > Back-end >  Problem to request data from express server with Axios
Problem to request data from express server with Axios

Time:01-07

I have an application in react on my domain with a server in Express.The project is divided into two sections (folders), "Frontend" and "Backend". When I start the express server it listens on port 4000, but when the application in React makes the request with axios through the path Ex:("https://localhost.com/dataRequested") get the 404 error. When I add the port to the domain of the listening server, the request work. Ex:("https://localhost.com:4000/dataRequested")

Index.js server Express

const routesHandler = require('./routes/handler.js');
const bodyParser = require('body-parser');
const https = require('https');
const fs = require('fs');
var privateKey  = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');

const credentials = {key: privateKey, cert: certificate};
const express = require('express');

const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use('/', routesHandler);

const httpsServer = https.createServer(credentials, app);

httpsServer.listen(4000);

handler.js route server Express

router.get('/randomElementsData', (req, res) =>
{
  //functions
}

hero.js component React app

const getHeroData = async () =>
{
   try
   {
      const response = await axios.get('/randomElementsData');
      setDataHero(response);
   }
   catch (error)
   {
      console.log(error);
   }
}

CodePudding user response:

Probably CORS issue if the react app is stand alone..

try adding this to express app

  app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', `http://${process.env.HOST}:${process.env.PORT_CLIENT}`) // update to match the domain you will make the request from
      res.header('Access-Control-Allow-Credentials', true)
      res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Auth-Token'
      )
      res.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT')
      if (req.method === 'OPTIONS') {
        res.status(204).send()
      } else {
        next()
      }
    })

CodePudding user response:

Add this to your package.json file

"proxy" : "http://localhost:4000"

this is used by react to send all fetch/axios requests to the node server (only in development). Then the node server should know whether to forward that request to the Reactjs router or to the express router

I add "/api" before all of my API calls to help express figure out which router to use

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

// All other GET requests not handled before will return our React app

app.get("/*", (req, res) => {
  res.sendFile(<the location of your build folder>);
// res.sendFile(path.join(__dirname, '/build'));
});

and now your axios call will look like

axios.get('/api/randomElementsData')

CodePudding user response:

Try hitting the endpoint http://localhost:4000/dataRequested

This may even be because of URL being Invalid

  •  Tags:  
  • Related