Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

javascript - 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);
  });
};
question from:https://stackoverflow.com/questions/65872602/why-cant-i-call-localhost-localhost5000-from-localhost3000-using-axios-in-rea

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...