简体   繁体   中英

React proxy doesn't work on npm run build

I'm trying to commnunicate with back-end server by using axios. So I added proxy in package.json like below.

package.json

  "proxy": "http://backend:8080",

It works well with 'npm start', but when I try 'npm run build', I am unable to communicate with the backend.

 axios.get('/member/login',{
        headers :{
          Authorization : hash
        }
      })

So I tried to put full url like below but still not communicating.

 axios.get('http://backend:8080/member/login',{
        headers :{
          Authorization : hash
        }
      })

How can I solve this problem??

It seems to be deployed through server.js after npm run build.So just in case, I'll upload the server.js code as well.

server.js

const http=require("http");
const express = require("express");
const path = require("path");

const app = express();

const port = 3000;

app.get("/ping",(req,res) =>{
    res.send("pong");
});

app.use(express.static(path.join(__dirname,"build")));
app.use('/', express.static(__dirname+'/server/build'))

app.get("/*",(req,res) => {
    res.set({
        "Cache-Control":"no-cache, no-store, must-revalidate",
        Pragma:"no-cache",
        Date:Date.now()
    });
    res.sendFile(path.join(__dirname,"build","index.html"));
});

http.createServer(app).listen(port,()=>{
    console.log(`app listening arr ${port})`);
});

React uses http://localhost:3000/ by default, backend port could be anything other than 3000. say if the backend port is 8080, then url to get data: http://localhost:8080/

proxy feature is only for development (with npm start ). witch means It is not meant for production (with npm build ). you can check it here

In production ( npm run build ) it just creates the static files to deploy which makes proxying doesn't make sense because there is no development server in this phase. instead, now you'll have to serve your static files on any server you choose. For example, in nginx server you can use proxy_pass

You could try using defaults :

axios.defaults.baseURL = 'http://backend:8080';

Did you install and import axios?

npm install axios

import axios from 'axios';

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