从角度8向Express.js后端Docker容器发送HTTP请求时,跨域请求被阻止(原因:CORS请求未成功)

时间:2020-07-26 21:41:05

标签: node.js angular docker cors

我正在运行2个docker容器,frontendbackend。前端在端口4200上运行Angular 8,后端在端口8080上运行Express.js。每当我向后端发送http请求时,就像这样:

getMeetings(): Observable<MeetingList> {
    // The url is http://backend:8080/backend/scheduled-meetings
    return this.http.get<MeetingList>(environment.backend + '/scheduled-meetings';);
}

我在控制台中收到此错误:

跨域请求被阻止:“同源起源”策略不允许读取位于http:// backend:8080 / backend / scheduled-meetings的远程资源。 (原因:CORS请求未成功。)

这是我的docker-compose.yml文件:

version: '3'
services:
  backend:
    container_name: backend
    build: ./backend
    ports:
      - '8080:8080'
    command: npm run start
    volumes: 
      # Mount the host path, ., to the path "/usr/src/app" in the docker container.
      # Do this so that nodemon can watch for file changes and restart within the container.
      # Should move to a src folder.
      - ./backend:/usr/src/app
  frontend:
    container_name: frontend
    build: ./frontend
    ports:
      - '4200:4200' # Port mapping
    volumes:
      - './frontend:/usr/src/app'

这里是有角容器的Dockerfile

FROM node:12

# Create working directory and make it the working directory
WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install -g @angular/cli @angular-devkit/build-angular && npm install

# Bundle the app source
COPY . /usr/src/app

EXPOSE 4200

CMD ["npm", "start"]

这是Express容器的Dockerfile

FROM node:12

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 8080

CMD [ "npm", "start"] 

我在Express应用程序中尝试了以下操作:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

我还通过在"proxyConfig": "src/proxy.conf.json"中添加angular.json来在Angular项目中使用代理,如下所示:

"serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
        "browserTarget": "frontend:build",
        "proxyConfig": "src/proxy.conf.json",
        "optimization": false
    },
...

并使用package.json中的以下命令为项目提供服务:

"scripts": {
    "start": "ng serve --host=0.0.0.0 --port 4200 --proxy-config src/proxy.conf.json",
    ...
}

这是proxy.conf.json文件:

{
    "/backend/*": {
        "target": "http://backend:8080",
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug",
        "pathRewrite": {
            "^/backend": ""
        }
    }
}

为什么会发生此错误?我以为在Node.js中添加Access-Control-Allow-Origin标头可以解决此问题,但不能解决。现在,我已经在Angular中使用代理尝试了其他几种配置,但仍然收到此错误。

1 个答案:

答案 0 :(得分:0)

如果您只是想使其工作(我很确定是这种情况),则允许任何cors请求对您都可以。只需安装cors并添加

app.use(require('cors')());

将解决您的问题。有关更多配置和信息,请参阅本指南https://expressjs.com/en/resources/middleware/cors.html

Angular代理用于开发,而不是在生产环境中运行。如果您不知道解决了什么确切的问题,请不要使用它