在AWS API网关中,要解决“Access-Control-Allow-Origin”头部缺失的问题,可以通过以下几种方法:
以下是使用AWS API网关的CORS功能的示例代码:
// AWS API Gateway CORS configuration
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*", // Replace * with your allowed origin(s)
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET" // Replace with your allowed methods
},
body: JSON.stringify({ message: "Hello, CORS!" })
};
// Lambda function handler
exports.handler = async (event) => {
// Process your Lambda function logic here
return response;
};
以下是在Lambda函数中手动添加“Access-Control-Allow-Origin”头部的示例代码:
// Lambda function handler
exports.handler = async (event) => {
// Process your Lambda function logic here
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*", // Replace * with your allowed origin(s)
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET" // Replace with your allowed methods
},
body: JSON.stringify({ message: "Hello, CORS!" })
};
return response;
};
通过以上两种方法之一,您可以在AWS API网关中解决“Access-Control-Allow-Origin”头部缺失的问题,并允许跨域访问。