我有一个公开的 Gitlab 存储库来演示这个问题: https ://gitlab.com/publ6/cors-is-my-friend
它可以与 Gitpod 一起使用。
这是一个带有 python Flask API 的 mono-repo,它公开了一个接受 GET 和 POST 请求的路由:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/method', methods = ['GET', 'POST'])
def post_method():
result = "result"
return result
还有一个由 vue-js (vite) 驱动的前端应用程序两次调用路由:使用 GET 请求,然后使用 POST 请求:
<script setup>
import { ref, onMounted } from 'vue'
import { get, post } from 'axios'
var get_result = ref(`waiting for get results from ` + import.meta.env.VITE_BACK_URL);
var post_result = ref(`waiting for post results from ` + import.meta.env.VITE_BACK_URL);
onMounted(() => {
getResult()
postResult()
})
function getResult () {
get(import.meta.env.VITE_BACK_URL + '/method', { withCredentials: true })
.then(response => {
get_result.value = response.data
})
}
function postResult () {
post(import.meta.env.VITE_BACK_URL + '/method', { withCredentials: true })
.then(response => {
post_result.value = response.data
})
}
</script>
<template>
<p>{{ get_result }}</p>
<p>{{ post_result }}</p>
</template>
<style scoped>
</style>
尽管使用了 python 库“flask_cors”,但在 Gitpod 中使用时出现 CORS 错误(它适用于 localhost)
Access to XMLHttpRequest at 'https://3000-publ6-corsismyfriend-e65siyrdx0x.ws-eu31.gitpod.io/method' from origin 'https://8000-publ6-corsismyfriend-e65siyrdx0x.ws-eu31.gitpod.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Failed to load resource: net::ERR_FAILED
Uncaught (in promise) Error: Network Error
at createError (axios.js:312:19)
at XMLHttpRequest.handleError (axios.js:606:18)
值得注意的是,我认为 Gitpod 测试很容易抛出 CORS 错误,即使它与 CORS 无关。