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

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

问题描述

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

 前端:
图片:< ; my_frontend_image>
端口:
- 3000:3000

api:
重新启动:始终
生成:./<my_api_folder>
端口:
- 9002:9002

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

  / emails / custom 

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

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

但是它不起作用,好像它向FrontEnd发送了一个请求



这里出了什么问题?



更新:
也许这个问题与某种原因有关到我的Nginx配置:

  location / {
#定义将请求发送到的代理服务器的位置
#Web是带有前端的docker容器的名称。
proxy_pass http:// frontend:3000;

#重新定义NGINX发送到上游服务器$ b的标头字段$ b proxy_set_header主机$ host;
proxy_set_header X-Real-IP $ remote_addr;
proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;

#定义文件上传的最大文件大小
client_max_body_size 5M;
}

#设置与API容器的通信。
location / api {
重写 ^ / api /(.*)$ / $ 1中断;
proxy_pass http:// api:9002;
proxy_redirect关闭;
proxy_set_header主机$ host;
}


解决方案

您正在尝试访问api服务是从浏览器外部获取的,而不是从可访问api主机名的前端容器内部获取的。端口转发是由docker完成的,因此在外部,您需要访问主机。例如: http:// localhost:9002 (例如,如果您在Mac上使用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"

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"
  ...

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

What is wrong here?

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;
}

解决方案

You are trying to access the api service externally from the browser not from within the frontend container which is where the api hostname is accessible. Port forwarding is done by docker so externally you need to hit the host. Eg.: http://localhost:9002 (if your using docker for mac for example)

A similar question/answer can be found here

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

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