[英]wget works but can't request from React app
I have two linked Docker containers api
and frontend
. 我有两个链接的Docker容器
api
和frontend
。 frontend
is a ReactJS app inside nginx
container. frontend
是nginx
容器内的ReactJS应用。 This is the Dockerfile: 这是Dockerfile:
FROM nginx:alpine
COPY ./build /usr/share/nginx/html/
and the run command: 和运行命令:
docker run --name frontend --link api:api -p 80:80 frontend_img
When I sh
inside frontend
and run: 当我
sh
内部frontend
和运行:
$ wget http://api:8080/api/users
works fine and I'm able to fetch the users. 工作正常,我能够获取用户。 However, when my app tries to fetch the data, I'm getting
ERR_NAME_NOT_RESOLVED
error in the Chrome console. 但是,当我的应用尝试获取数据时,我在Chrome控制台中收到
ERR_NAME_NOT_RESOLVED
错误。
This is my JS code: 这是我的JS代码:
fetchUsers() {
return axios.get('http://api:8080/api/users')
.then(response => response.data)
.then(users => this.setState({ users }));
}
What am I missing? 我想念什么? Do I need to configure something in NGINX in order to be able to fetch the data from the
api
or something? 我是否需要在NGINX中配置某些内容以便能够从
api
或其他内容中获取数据?
Solved! 解决了! Thanks to this accepted answer docker nginx ERR_NAME_NOT_RESOLVED
感谢这个公认的答案, 码头工人nginx ERR_NAME_NOT_RESOLVED
When connecting to containers with a reverse proxy, all the URL's used by the application need to point to that reverse proxy and not the application.
当使用反向代理连接到容器时,应用程序使用的所有URL都必须指向该反向代理,而不是应用程序。 Typically you do this by giving a path in the URL without a hostname.
通常,您可以通过在URL中提供不带主机名的路径来实现。
First, I created a default.conf
nginx file to add a location
statement to redirect calls to my api container: 首先,我创建了
default.conf
nginx文件,以添加location
声明以将调用重定向到我的api容器:
location /api/ {
proxy_pass http://api:8080;
}
Then, in my webapp, I change my JS code so I request against /api/users
, without hostname: 然后,在我的web应用程序中,更改我的JS代码,以便针对
/api/users
请求,而不使用主机名:
fetchUsers() {
return axios.get('/api/users')
.then(response => response.data)
.then(users => this.setState({ users }));
}
Finally, in the Dockerfile, I replace default default.conf
nginx file with the edited one: 最后,在Dockerfile中,我将默认的
default.conf
nginx文件替换为已编辑的文件:
FROM nginx:alpine
COPY default.conf /etc/nginx/conf.d
COPY ./build /usr/share/nginx/html/
That's all! 就这样!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.