【问题标题】:wget works but can't request from React appwget 工作,但无法从 React 应用程序请求
【发布时间】:2019-02-02 09:53:41
【问题描述】:

我有两个链接的 Docker 容器 apifrontendfrontendnginx 容器内的 ReactJS 应用程序。这是 Dockerfile:

FROM nginx:alpine

COPY ./build /usr/share/nginx/html/

和运行命令:

docker run --name frontend --link api:api -p 80:80 frontend_img

当我 shfrontend 中运行时:

$ wget http://api:8080/api/users

工作正常,我可以获取用户。但是,当我的应用尝试获取数据时,我在 Chrome 控制台中收到 ERR_NAME_NOT_RESOLVED 错误。

这是我的 JS 代码:

fetchUsers() {
    return axios.get('http://api:8080/api/users')
      .then(response => response.data)
      .then(users => this.setState({ users }));
}

我错过了什么?我是否需要在 NGINX 中配置一些东西才能从api 或其他东西中获取数据?

【问题讨论】:

    标签: reactjs http docker nginx wget


    【解决方案1】:

    解决了!感谢这个被接受的答案docker nginx ERR_NAME_NOT_RESOLVED

    当使用反向代理连接到容器时,所有的 URL 都会被使用 由应用程序需要指向该反向代理而不是 应用。通常,您通过在 URL 中提供一个路径来执行此操作,而无需 主机名。

    首先,我创建了一个default.conf nginx 文件来添加一个location 语句来将调用重定向到我的api 容器:

    location /api/ {
      proxy_pass http://api:8080;
    }
    

    然后,在我的 webapp 中,我更改了我的 JS 代码,因此我请求 /api/users,没有主机名:

    fetchUsers() {
        return axios.get('/api/users')
          .then(response => response.data)
          .then(users => this.setState({ users }));
    }
    

    最后,在 Dockerfile 中,我将默认的default.conf nginx 文件替换为编辑后的文件:

    FROM nginx:alpine
    COPY default.conf /etc/nginx/conf.d
    COPY ./build /usr/share/nginx/html/
    

    就是这样!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      相关资源
      最近更新 更多