在前端 JS 中将 ajax 请求从一个容器发送到另一个容器 [英] Send ajax request in front end JS from one container to another

查看:47
本文介绍了在前端 JS 中将 ajax 请求从一个容器发送到另一个容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 API 和前端使用了不同的 Docker 容器.

I'm using different Docker containers for API and front-end.

frontend:
  image: <my_frontend_image>
  ports:
   - "3000:3000"

api:
  restart: always
  build: ./<my_api_folder>
  ports:
   - "9002:9002"

在 API 端,我有发送电子邮件的端点:

On API side I have the endpoint for sending emails:

/emails/custom

在前端,我正在尝试向此端点发送请求:

On frontend side I'm trying to send a request to this endpoint:

$.ajax({
  url: "http://api:9002/api/emails/custom",
  dataType: "json",
  type: "POST"
  ...

但它不起作用.看起来它又向 FrontEnd 容器发送了请求.

But it doesn't work. It looks like it sends a request to FrontEnd container again.

这里出了什么问题?

更新:也许这个问题也与我的 nginx 配置有关:

UPDATE: Maybe this issue is somehow related to my nginx configurations too:

location / {
    # Define the location of the proxy server to send the request to
    # Web it's a name of docker container with frontend.
    proxy_pass http://frontend:3000;

    # Redefine the header fields that NGINX sends to the upstream server
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    # Define the maximum file size on file uploads
    client_max_body_size 5M;
}

# Setup communication with API container.
location /api {
    rewrite "^/api/(.*)$" /$1 break;
    proxy_pass http://api:9002;
    proxy_redirect     off;
    proxy_set_header   Host $host;
}

推荐答案

我已经更仔细地研究了您的问题.你不能做你想做的事,因为浏览器真的总是使用本地env来发出ajax请求,而在那个envapi"不存在的情况下,它查看自己的hosts文件并找不到它,最后失败.

I have look into your problem more carefully. You can't do what you tryint to do, because browser really always use local env to make ajax requests, and in that env "api" dose not exist, it look at its own hosts file and can't find it, and finally fail.

您需要更新前端代码以根据它所在的位置进行请求.

  var url = document.location.protocol + "//" + document.location.hostname + ":9002";
  var api = url + "/api/emails/custom"
  $.ajax({
    url: api,
    dataType: "json",
    type: "get",
  });
}

您也可以在本地主机文件中将api"正确解析为ip地址,但我认为这是更明智的解决方案.我还在这里制作了工作版本:

You can also correctly resolve "api" to ip address in your local hosts file, but I think this is more sensible solution. I also made working version here:

注意:我已将 POST 请求更改为 GET 请求.

NOTE: I made change from POST to GET request.

这篇关于在前端 JS 中将 ajax 请求从一个容器发送到另一个容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆