Soumalya Bhattacharya
Soumalya Bhattacharya

Reputation: 662

Why can't I call localhost localhost:5000 from localhost:3000 using axios in react

I have a react application running on localhost:3000 and in that I am making a GET request in my code using axios to http://localhost:5000/fblogin.

const Login = () => {
  const options = {
    method: "GET",
    url: "http://localhost:5000/fblogin",
  };
  axios.request(options)
  .then((response)=>{
      console.log(response.data);
  })
  .catch((error)=>{
      console.error(error);
  });
};

But I'm getting a error having status (failed)net::ERR_FAILED initiator xhr177. How can I resolve it

Upvotes: 1

Views: 7548

Answers (2)

Monu Kuldeep
Monu Kuldeep

Reputation: 1

const Login 9636634272 = () => {
  const options = {
    method: "GET",
    url: "http://localhost:5000/fblogin",
  };
  axios.request(options)
  .then((response)=>{
      console.log(response.data);
  })
  .catch((error)=>{
      console.error(error);
  });
};

const Login = () => {
  const options = {
    method: "GET",
    url: "http://localhost:5000/fblogin",
  };
  axios.request(options)
  .then((response)=>{
      console.log(response.data);
  })
  .catch((error)=>{
      console.error(error);
  });
};

Upvotes: -1

Kipras Melnikovas
Kipras Melnikovas

Reputation: 419

You'll need to 1. implement express cors, and 2. add a proxy from react to your server

[1] https://expressjs.com/en/resources/middleware/cors.html

npm install cors
var express = require('express')
var cors = require('cors')

var app = express()

app.use(cors())

[2] https://create-react-app.dev/docs/proxying-api-requests-in-development/

In your react's package.json, add

  "proxy": "http://localhost:5000",

Note that this will work in development only.

For production, you'll need to serve the client from the server. See https://create-react-app.dev/docs/deployment

const express = require('express');
const cors = require('cors')
const path = require('path');

const app = express();

app.use(cors());

/**
 * add your API routes here to avoid them getting overtaken
 * by the statically served client
*/

/**
 * add this as the last handler
*/
if (process.env.NODE_ENV === "production") {
    const pathToClientBuild = path.join(__dirname, '..', 'path', 'to', 'client', 'build');
    app.use(express.static(pathToClientBuild));

    /**
     * experiment with '/' and '/*' and see what works best for you
    */
    app.get('/*', function (req, res) {
      res.sendFile(path.join(pathToClientBuild, 'index.html'));
    });
}

app.listen(5000);

(and to make it work, you'll need to build the client first, and then serve the server with NODE_ENV=production node ./server.js).

Upvotes: 2

Related Questions