前端无法向后端发送 json:跨域请求被阻止

时间:2021-07-08 14:08:29

标签: json axios request cors containers

我有两个容器,一个用 VueJS 前端,另一个用 python/flask 后端。使用 docker compose,我在 2 个容器之间建立了通信。 docker 网络没问题,因为在前端容器中我可以 ping 后端容器。但是当前端应用向后端发送一个 json 时,会出现这个错误:

<块引用>

跨域请求被阻止:同源策略不允许读取 位于 http://backend1:5000/test/ 的远程资源。 (原因:CORS 请求没有成功)。

Docker-Compose 文件:

version: "3"

services:
  backend1-compose:
    build:
      context: .
      dockerfile: ./backend1.dockerfile
    container_name: backend1
    ports:
      - "5000:5000"
    volumes:
      - ../backend/:/backend/
    networks:
      - network1-compose

  frontend1-compose:
    build:
      context: .
      dockerfile: ./frontend1.dockerfile
    container_name: frontend1
    ports:
      - "8080:8080"
    volumes:
      - ../frontend/:/app/
    command: npm run serve
    depends_on:
      - backend1-compose
    networks:
      - network1-compose
  
networks:
  network1-compose:
    driver: bridge

在前端,我配置了一个 axios 插件:

import Vue from 'vue'
import axios from 'axios'

Vue.use({
    install(Vue) {
        Vue.prototype.$http = axios.create({
            baseURL: 'http://backend1:5000/',
            headers: {
                'Content-Type': 'application/json',
            },
        })
    }
})

在后端:

app = Flask(__name__, static_url_path="/static")
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['CORS_RESOURCES'] = {r"/test/": {"origins": "*"}}

cors = CORS(app)

@app.route('/test/', methods=['POST', 'OPTIONS'])
@cross_origin(origin='*', headers=['Content-Type','Origin',  'X-Auth-Token'])
def reply():
    ...

有什么想法吗?

0 个答案:

没有答案