从 Vue.js 组件到具有快速网关的服务器的 HTTP 请求存在问题。我认为问题出在 Express Gateway 上,因为即使应该接收请求的微服务处于脱机状态,错误仍然会显示。
Vue.js 代码非常简单,就是:
await this.$http.post('http://localhost:8080/cartItems/',{
user_id: this.userId,
product_id: this.productId,
quantity: productQuantity,
},{
headers:{
'Access-Control-Allow-Origin': '*',
}
}).then(response => {
Vue.$toast.open({
position: 'bottom-right',
type: 'success',
duration: 3000,
message: '--------',
});
})
.catch(errors => {
Vue.$toast.open({
position: 'bottom-right',
type: 'error',
duration: 3000,
message: '--------',
});
});
控制台中的错误是:
Access to XMLHttpRequest at 'http://localhost:8080/cartItems/' from origin 'http://localhost:10000' 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.
奇怪的事情(对我来说很奇怪)是问题只出现在 POST 请求中,但它没有出现在 GET 请求中。
我按照文档使用 cors 策略(见下文)配置了网关,但我不知道我做错了什么。
policies:
- cors
......
pipelines:
cart:
apiEndpoints:
- cart-view-update-delete
- cart-add
- cart-my
policies:
- cors:
- action:
origin: '*'
methods: ['HEAD','PUT','PATCH','POST','DELETE']
- proxy:
- action:
serviceEndpoint: cart
changeOrigin: true