Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Docker&x2B;烧瓶+;反应+;Axios+;http代理中间件失败,错误为“0”;尝试代理到…“时出错”;_Reactjs_Docker_Flask_Axios_Http Proxy Middleware - Fatal编程技术网

Reactjs Docker&x2B;烧瓶+;反应+;Axios+;http代理中间件失败,错误为“0”;尝试代理到…“时出错”;

Reactjs Docker&x2B;烧瓶+;反应+;Axios+;http代理中间件失败,错误为“0”;尝试代理到…“时出错”;,reactjs,docker,flask,axios,http-proxy-middleware,Reactjs,Docker,Flask,Axios,Http Proxy Middleware,我对http代理中间件有一个问题 我的设置是,我在docker容器中有我的flask API和我的React前端,从docker compose文件运行。一切都很好。烧瓶打开localhost:5000并在localhost:3000 我的Flask API正在通过路由localhost:5000/最近的客户侦听POST请求 使用Postman,我可以发送一些信息并获得格式良好的JSON响应。它工作得很好 问题是,当我尝试使用http代理中间件调用sayhttp://localhost:3000

我对http代理中间件有一个问题

我的设置是,我在
docker容器
中有我的
flask API
和我的
React前端
,从
docker compose
文件运行。一切都很好。烧瓶打开
localhost:5000
并在
localhost:3000

我的Flask API正在通过路由
localhost:5000/最近的客户
侦听
POST
请求

使用
Postman
,我可以发送一些信息并获得格式良好的JSON响应。它工作得很好

问题是,当我尝试使用http代理中间件调用say
http://localhost:3000/api/recent_customers
哪个应该路由到
http://localhost:5000/recent_customers
我发现以下错误:

尝试代理到以下位置时出错:localhost:3000/api/recent_customers

使用React,我设置了
http代理中间件
,并将
setupProxy.js
设置为:

  const { createProxyMiddleware } = require("http-proxy-middleware");

  module.exports = function (app) {
    app.use(
      "/api",
      createProxyMiddleware({
        target: "http://localhost:5000",
        changeOrigin: true,
      })
    );
  };
  import axios from "axios";

  const instance = axios.create({
    baseURL: "/api",
  });

  instance.defaults.headers.common["Authorization"] = "AUTH TOKEN FROM INSTANCE";

  // instance.interceptors.request...

  export default instance;
我已将我的
Axios
设置为:

  const { createProxyMiddleware } = require("http-proxy-middleware");

  module.exports = function (app) {
    app.use(
      "/api",
      createProxyMiddleware({
        target: "http://localhost:5000",
        changeOrigin: true,
      })
    );
  };
  import axios from "axios";

  const instance = axios.create({
    baseURL: "/api",
  });

  instance.defaults.headers.common["Authorization"] = "AUTH TOKEN FROM INSTANCE";

  // instance.interceptors.request...

  export default instance;
我将axios导入我的
React组件
,为了清晰起见,这是它的裁剪版本:

 import React, { useEffect, useState } from "react";

    import RecentCustomersList from "../../components/Home/RecentCustomerList/RecentCustomerList";

    import axios from "../../axios";

    export default function Home(props) {
    
    // total number of active customers in the system
    const [totalActiveCustomers, setTotalActiveCustomers] = useState(
        "calculating."
    );

    // list of a few customers that have been added recently
    const [recentCustomers, setRecentCustomers] = useState([]);

    
    // This is currently taking temp JSON data.  We will take this from our API with axios in time
    const recentCustomersHandler = () => {
        axios.post("/recent_customers").then((response) => {
        const customers = response.data;
        setRecentCustomers(customers);
        });
    };

    // load the axios API data to be sent to the recent customers
    useEffect(() => {
        recentCustomersHandler();
    }, []);

    // more here for prepping the display of data

    return (
        <div>
        <Grid container spacing={3}>
            {/* more layout here but trimmed for clarity */}
            <RecentCustomerListGridItem />
        </Grid>
        </div>
    );
    }
我的
docker compose
文件在这里:

  version: "3.7"

  services:
    # react
    client:
      container_name: react
      build:
        context: ./frontend
        dockerfile: Dockerfile
      tty: true
      ports:
        - "3000:3000"
      volumes:
        - ./frontend:/app
        - /app/node_modules
      networks:
        - frontend
      depends_on:
        - flask_api

    # flask
    flask_api:
      container_name: flask-api
      build:
        context: ./backend
        dockerfile: Dockerfile
      command: gunicorn --reload --bind 0.0.0.0:5000 flask_api.app:create_app()
      ports:
        - "5000:5000"
      volumes:
        - ./backend:/app #  mount the /backend folder to the docker's /app directory. This allows for hotloading in flask, so when I save locally, container updates
        - appdata:/var/www/
      networks:
        - frontend
        - backend

  networks:
    frontend:
      driver: bridge
    backend:
      driver: bridge

  volumes:
    appdata:
      driver: local
我想知道是否有人能发现问题。如果我遗漏了任何可能有用的信息,请务必让我知道,我会回答这个问题。多谢各位

更新1: 如果我将axios文件更新为以下内容:

import axios from "axios";

const instance = axios.create({
  baseURL: "http://localhost:5000",
});

instance.defaults.headers.common["Authorization"] = "AUTH TOKEN FROM INSTANCE";

// instance.interceptors.request...

export default instance;
我仍然从
邮递员那里收到相同的错误,但是我在react/浏览器中的控制台显示为此错误:


跨源请求被阻止:同一源策略不允许读取远程资源http://localhost:5000/recent_customers. (原因:CORS请求未成功)。

我终于能够使用反向代理使用nginx托管我的应用程序

首先,你必须使用Docker的多级构建,这样你就可以使用nginx来托管你的应用程序。下面是一个Docker配置示例:

# build environment
FROM node:13.12.0-alpine as build
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package.json ./
COPY package-lock.json ./
RUN npm ci --silent
RUN npm install react-scripts@3.4.1 -g --silent
COPY . ./
RUN npm run build

# production environment
FROM nginx:stable-alpine
COPY --from=build /app/build /usr/share/nginx/html
# new
COPY nginx/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
此配置中有几个关键点:

  • 在构建的第一阶段,我安装
    react scripts
    ,这样我就可以在Docker的上下文中创建我的应用程序的生产构建,这样我们就可以在第二阶段使用该输出。在第二阶段,我创建了一个托管我的应用程序的nginx构建
  • 为nginx创建一个配置文件——在我的例子中,我刚刚调用了它
    nginx.conf
  • nginx.conf
    中,您可以设置应用程序的主入口点,该入口点为react应用程序提供服务。然后,添加一个反向代理以指向实际的API。这是我的配置:

    server {
    
      listen 80;
    
      location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
      }
    
      location /api {
        proxy_pass http://api.your-domain.com;
      }
    
      error_page   500 502 503 504  /50x.html;
    
      location = /50x.html {
        root   /usr/share/nginx/html;
      }
    
    }
    
    location/
    是应用程序的主要入口点,在这里您可以指定所有内容都路由到
    index.html


    有趣的部分是
    location/api
    ——这是允许应用程序通过中间件代理与api通信所需的反向代理。在React应用程序中,所有内容都转到
    /api/someEndpoint
    ——我创建了一个
    api.ts
    文件,以确保每个调用都以
    /api
    开头。这一切对我来说都非常好,应用程序运行良好,对我后端的调用非常快。希望这能有所帮助:)

    你能解决这个问题吗?我现在正试图将React应用程序与http代理中间件对接时遇到了这个问题。我创建了使用nginx运行应用程序的容器,但在尝试从应用程序发出任何POST请求时,我刚刚收到一个405错误。不幸的是,没有。项目处于搁置状态。我的CORS错误总数。我让它工作了一段时间,但它回来了,我不知道它是什么。所以沮丧的我把项目搁置下来冷静下来,然后再回来。如果你能弄明白,写一篇关于你所做的事情的帖子将不胜感激。