繁体   English   中英

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

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

我正在尝试使用 axios 与后端服务器通信。 所以我在 package.json 中添加了代理,如下所示。

package.json

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

它适用于“npm start”,但是当我尝试“npm run build”时,我无法与后端通信。

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

因此,我尝试将完整的 url 如下所示,但仍然无法通信。

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

我怎么解决这个问题??

好像是npm运行构建后通过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/

代理功能仅用于开发(使用npm start )。 女巫意味着它不适用于生产(使用npm build )。 你可以在这里查看

生产中( npm run build )它只是创建 static 文件来部署,这使得代理没有意义,因为在这个阶段没有开发服务器。 相反,现在您必须在您选择的任何服务器上提供您的 static 文件。 例如,在nginx 服务器中,您可以使用proxy_pass

您可以尝试使用默认值

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

您是否安装并导入了 axios?

npm 安装 axios

从'axios'导入axios;

暂无
暂无

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

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