首页 > 解决方案 > CORS 问题 - preflightMissingAllowOriginHeader - Express Gateway 和 Axios

问题描述

我很想使用 Express Gateway + AXIOS (react) + Express,但我收到了 CORS Erro,我已经做了很多事情但没有任何效果。

错误是这样的: 在此处输入图像描述

Cross-Origin Resource Sharing error: PreflightMissingAllowOriginHeader

EXPRESS的是这样的:

const corsOptions = {
    origin: '*',
    methods: ['POST', 'GET', 'PATCH', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization']
}
app.use(cors(corsOptions));

我的EXPRESS-GATEWAY

http:
  port: 8080
admin:
  port: 9876
  host: localhost
apiEndpoints:
  api:
    host: "localhost"
    paths: 
      - '/api/B/*'
      - '/api/A/*'
serviceEndpoints:
  appname:
    urls: 
      - 'http://localhost:8000'
policies:
  - jwt
  - cors
  - expression
  - log
  - proxy
  - rate-limit
pipelines:
  default:
    apiEndpoints:
      - api
    policies:
      - cors:
          - action:
              origin: ["*"]
              methods: [ "HEAD", "PUT", "PATCH", "POST", "GET", "DELETE" ]
              credentials: true
              allowedHeaders: ['Content-type','Authorization','Origin','Access-Control-Allow-Origin','Accept','Options','X-Requested-With']
      - jwt:
          - action:
              secretOrPublicKey: code
              checkCredentialExistence: false
      - proxy:
          - action:
              serviceEndpoint: appname
              changeOrigin: true

我的AXIOS

const headers = {
  headers: {
    "Authorization": authToken,
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Credentials": true
  },
}

axios.get(`${API_PRIVATE_URL}/user/profile`, {
  crossdomain: true
}, {
  withCredentials: true
}, headers)

我不知道该怎么办了。有人能帮我吗 ?

我已经进入了几个帖子,但没有任何效果..

编辑:它也没有进入控制器。edit2:我可以与 POSTMAN 一起使用,它按预期工作......

标签: expressaxiosexpress-gateway

解决方案


在 express/express-gateway 的允许方法列表中的“DELETE”之后添加“OPTIONS”。

const corsOptions = {
    origin: '*',
    methods: ['POST', 'GET', 'PATCH', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization']
}
app.use(cors(corsOptions));

http:
  port: 8080
admin:
  port: 9876
  host: localhost
apiEndpoints:
  api:
    host: "localhost"
    paths: 
      - '/api/B/*'
      - '/api/A/*'
serviceEndpoints:
  appname:
    urls: 
      - 'http://localhost:8000'
policies:
  - jwt
  - cors
  - expression
  - log
  - proxy
  - rate-limit
pipelines:
  default:
    apiEndpoints:
      - api
    policies:
      - cors:
          - action:
              origin: ["*"]
              methods: [ "HEAD", "PUT", "PATCH", "POST", "GET", "DELETE", "OPTIONS" ]
              credentials: true
              allowedHeaders: ['Content-type','Authorization','Origin','Access-Control-Allow-Origin','Accept','Options','X-Requested-With']
      - jwt:
          - action:
              secretOrPublicKey: code
              checkCredentialExistence: false
      - proxy:
          - action:
              serviceEndpoint: appname
              changeOrigin: true


推荐阅读