这真让我感到困惑。我已经在AWS Lambda中使用aws npx cli test命令测试了以下API,并且在这两者上均有效。当我提交表单时从客户端调用api时会出现问题。我收到以下错误
Access to XMLHttpRequest at 'https://sdigg5u4xb.execute-api.eu-west-1.amazonaws.com/prod/sites' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我已经在我的serverless.yml文件上尝试禁用了cors。我尝试使用不同的IAM角色,并且尝试在客户端代码中以不同的方式调用它。
我在这里调用API:
import { API } from "aws-amplify";
export default (async function submitSite(values) {
console.log(JSON.stringify(values));
return API.post("sites", "sites", {
body: values
})
});
这是在serverless.yml文件中定义我的API的地方
createSite:
handler: CreateSite.main
events:
- http:
path: sites
method: post
cors: true
authorizer: aws_iam
这是api代码本身
import uuid from "uuid";
import * as dynamoDbLib from "./libs/dynamodb-lib";
import { success, failure } from "./libs/response-lib";
export async function main(event, context) {
const data = JSON.parse(event.body);
const params = {
TableName: "sites",
Item: {
userId: event.requestContext.identity.cognitoIdentityId,
siteId: uuid.v1(),
siteName: data.siteName,
siteAddress: data.siteAddress,
siteCounty: data.siteCounty,
siteEmail: data.siteEmail,
siteNumber: data.siteNumber,
openTimes: data.openTimes,
siteCat: data.siteCat,
siteFees: data.siteFees,
access: data.access,
w3w: data.w3w,
gps: data.gps,
detailsHeader: data.detailsTxtHeader,
detailsContent: data.detailsTxtContent,
tourName: data.tourName,
tourWaypoints: data.waypoints,
tourDuration: data.duration,
tourHeader: data.tourTxtHeader,
tourContent: data.tourTxtContent,
poiName: data.poiName,
poiType: data.poiType,
poiDesc: data.poiDesc,
poiDuration: data.poiDuration,
poiRanking: data.poiRanking,
poiTime: data.poiTime,
poiAccess: data.poiAccess,
poiHeader: data.poiTxtHeader,
poiContent: data.poiTxtContent
}
};
try {
await dynamoDbLib.call("put", params);
return success(params.Item);
} catch (e) {
return failure({ status: false });
}
}
答案 0 :(得分:1)
您还需要在响应上设置CORS。因此,请在您的success()
方法中进行相应的调整(顺便说一句,您没有显示它,因此最好添加它,以防下面的代码不起作用):
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify(yourCustomObject),
};