Home > Software design >  React proxy doesn't work on npm run build
React proxy doesn't work on npm run build

Time:09-10

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

CodePudding user response:

Did you install and import axios?

npm install axios

import axios from 'axios';

CodePudding user response:

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/

CodePudding user response:

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

CodePudding user response:

You could try using defaults:

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