简体   繁体   English

React 代理在 npm 运行构建上不起作用

[英]React proxy doesn't work on npm run build

I'm trying to commnunicate with back-end server by using axios.我正在尝试使用 axios 与后端服务器通信。 So I added proxy in package.json like below.所以我在 package.json 中添加了代理,如下所示。

package.json 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.它适用于“npm start”,但是当我尝试“npm run build”时,我无法与后端通信。

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

So I tried to put full url like below but still not communicating.因此,我尝试将完整的 url 如下所示,但仍然无法通信。

 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.好像是npm运行构建后通过server.js部署的。所以为了以防万一,我也上传server.js代码。

server.js服务器.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/ 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 ).代理功能仅用于开发(使用npm start )。 witch means It is not meant for production (with npm build ).女巫意味着它不适用于生产(使用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.生产中( npm run build )它只是创建 static 文件来部署,这使得代理没有意义,因为在这个阶段没有开发服务器。 instead, now you'll have to serve your static files on any server you choose.相反,现在您必须在您选择的任何服务器上提供您的 static 文件。 For example, in nginx server you can use proxy_pass例如,在nginx 服务器中,您可以使用proxy_pass

You could try using defaults :您可以尝试使用默认值

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

Did you install and import axios?您是否安装并导入了 axios?

npm install axios npm 安装 axios

import axios from 'axios';从'axios'导入axios;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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