让 vue devServer 代理在 docker 中使用不同的本地端口

Getting vue devServer proxy to work with different local ports in docker

尝试正确设置这里有点疯狂。我在 docker 中有 Vue 运行 devServer,然后是一个单独的卷 运行 json-server,用于提供伪造的 api 数据。对于初学者,我很乐意让这个简单的示例运行,但我不断收到代理错误。这是我当前的配置。

docker-撰写:

version: "3.7"

services:
  front:
    container_name: front
    build: .
    volumes:
      - .:/app
      - ./node_modules:/app/node_modules
    ports:
      - '8080:8080'

  api:
    image: vimagick/json-server
    command: -H 0.0.0.0 -p 3000 -w db.json
    ports:
      - "3000:3000"
    volumes:
      - ./server/data:/data

Docker 文件:


FROM node:lts-alpine as front

# install simple http server for serving static content
RUN npm install -g @vue/cli

# make the 'app' folder the current working directory
WORKDIR /app

# Add necessary files to app
ENV PATH ./:/app/:./node_modules/.bin:$PATH
ENV NODE_ENV=development

# copy both 'package.json' and 'package-lock.json' (if available)
COPY package.json /app/package.json
COPY package-lock.json /app/package.lock.json

# install project dependencies
RUN npm install --silent

# copy project files and folders to the current working directory (i.e. 'app' folder)

COPY ./ .

EXPOSE 8080
CMD ["npm", "run", "serve"]

以上所有都可以正常工作。上面的所有内容都已构建,并且它们都在各自的端口上 运行。

我可以导航到 http://localhost:3000/posts,我看到了我期待的假 json。我可以在 http://localhost:8080/ 上进行热模块重新加载、开发等。现在问题来了。我想在 vue 应用程序中使用来自 json 服务器的数据,并且我想将我的请求从 http://localhost:8080/api/* 代理到 http://localhost:3000/。这是我的 Vue.Config 文件:

module.exports={
  devServer: {
      proxy: {
        "^/api/": {
          target: "http://localhost:3000/",
          secure: false,
          pathRewrite: {
            "/api/*": "/"
          }
        }
      }
    }
  };

然后在应用程序中,我提出 axios.get('/api/posts/') 之类的请求。我已经在所有三个文件中尝试了上述代码的大约 100 种不同的细微变化,但每次出现此错误时:

Proxy error: Could not proxy request /posts from localhost:8080 to http://localhost:3000/ (ECONNREFUSED).

我想我对它应该如何工作有一个根本性的误解,因为我已经遵循了每条说明并从 Vue 的说明中复制和粘贴。任何人都可以提供的任何见解将不胜感激

这里的问题是 localhost 的代理不正确。如果您将 vue 配置更改为以下内容,它应该可以工作:

module.exports={
  devServer: {
      proxy: {
        "^/api/": {
          target: "http://api:3000",
          secure: false,
          pathRewrite: {
            "/api/*": "/"
          }
        }
      }
    }
  };

基本上,更改是将主机从 localhost 替换为 api。原因是 docker-compose 通过服务名称解析主机。由于您的服务名称是 api,主机也应该是 api.

再说明一点,这里的主机不是从你机器的角度,而是从vue.js容器的角度。从 vue.js 容器的角度来看,api 是一个单独的主机(不再是本地主机)。希望这是有道理的 - 如果需要更多说明,lmk。