简体   繁体   中英

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

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 ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM