如何防止 nginx 在 Angular 应用程序中更改我的请求 URL

How do I prevent nginx from changing my request URL in Angular app

我正在尝试在 Docker 中构建我的 Angular 网站,这也有效,但每当网站发出请求时,URL 就会从 http://url_to_api 到 http://localhost:8080/url_to_api.

我对 NGINX 和 docker 还很陌生,尝试过许多不同的配置,但 none 奏效了。

我在浏览器中也收到错误:

Failed to load resource: net::ERR_CONNECTION_REFUSED  /assets/js/env.js

nginx 是否阻止了它?

这是我的基础nginx.conf

server {
  listen 80;
  location / {
    root /usr/share/nginx/html;
    index index.html;
    try_files $uri $uri/ /index.html;
  }
}

这里是 docker 文件


#stage 1
FROM node:12-alpine as build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build --prod
#stage 2
FROM nginx:alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist/webapp /usr/share/nginx/html
EXPOSE 80
#To provide environment variables in angular 
CMD ["/bin/sh",  "-c",  "envsubst < /usr/share/nginx/html/assets/js/env.template.js > /usr/share/nginx/html/assets/js/env.js && exec nginx -g 'daemon off;'"]

# Create image based on the official Node 10 image from dockerhub
FROM node:10

# Create a directory where our app will be placed
RUN mkdir -p /app

# Change directory so that our commands run inside this new directory
WORKDIR /app

# Copy dependency definitions
COPY package*.json /app/

# Install dependencies
RUN npm install

# Get all the code needed to run the app
COPY . /app/

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]

检查这里的步骤https://www.digitalocean.com/community/tutorials/create-a-mean-app-with-angular-2-and-docker-compose 为 angular2 客户端

学习和构建 docker

现在发现我的错误了。配置文件没问题,但是犯了一个非常愚蠢的错误,我在docker文件末尾的脚本已经交换了API URL但是我忘了在开头指定HTTP URL 等 Nginx 已在本地主机上请求 URL。