【发布时间】:2021-03-31 10:12:38
【问题描述】:
我正在尝试通过 AWS API Gateway 创建一个 API 测试函数和一个通过带有 Axios 的 Vue 应用程序调用的 Lambda 函数。它应该从输入元素发送名称和电子邮件。每次我收到此错误:
Access to XMLHttpRequest at '[API Gateway URL]' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
我已在 API 网关设置 (per this article) 中的每个步骤/资源上启用了 CORS。这是Vue组件的代码:
<template>
<div data-app>
<div class="cell" id="testForm">
{{responseMsg}}
<label>Name</label>
<input v-model="name" type="text" placeholder="Name">
<label>Email Address</label>
<input v-model="email" type="email" placeholder="Email Address">
<button v-on:click="formFunction">Submit</button>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: "formtest",
data: function () {
return {name: '',
email: '',
responseMsg: 'No response yet!'}
},
methods: {
formFunction: function () {
const formObj = {
name: this.name,
email: this.email
}
const reqURL = [API gateway URL];
axios.post(reqURL, formObj)
.then(response => {
console.log(response);
});
}
}
}
</script>
这是我的 Lambda 函数:
exports.handler = async (event) => {
const resString = 'Hello ' + event.name + ", your email address is " + event.email
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: resString,
};
return response;
};
我在这里做错了什么?
【问题讨论】:
-
您是否在服务器中为 POST 方法启用了 CORS?
-
您是否尝试过发送内容类型标头? axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
-
检查以确保在 API Gateway 中设置的 URL 与 Axios 调用的 URL 完全相同。因为 Axios 的第一个请求是 CORS 飞行前请求,所以如果你调用了错误的 URL,你会得到一个 CORS 失败错误而不是 404 not found 错误,例如。
-
虽然它应该自动发生,但如果您在 AWS 控制台中创建资源,请检查是否还配置了
OPTIONS方法。
标签: amazon-web-services vue.js aws-lambda axios aws-api-gateway