我有一个简单的应用程序。有一个 Lambda 函数返回一个简单的字符串作为正文,并返回 200 作为 statusCode。我有一个带有资源 (GoalGroup) 和 GET 方法的默认 API 网关。如果我在方法页面进行测试,它会正确执行并显示从 lambda 返回的字符串。同样,执行curl测试并显示Lambda函数返回的字符串。
当我尝试从前端代码调用 lambda 时,收到一条错误消息:
TypeError: Failed to fetch
前端代码如下:
fetch ("https://orofqutps8.execute-api.eu-north-1.amazonaws.com/prod/GoalGroup", {
method: 'GET',
})
.then(response => {
alert (`response:: ${response.status}`)
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
alert('Raw response:', response);
return response.json();
})
.then(data => {
// Process the data returned from the API
console.log('API response:', data);
alert('data:: ', JSON.stringify(data));
})
.catch(error => {
alert (`Error: ${error}`);
console.error('Error:', error);
});
至于 CORS(谢谢 Erik258),我在 Lambda 的响应中设置了标头。
我运行curl来测试:
>curl -v -X GET https://xy.execute-api.eu-north-1.amazonaws.com/prod/GoalGroup
Note: Unnecessary use of -X or --request, GET is already inferred.
* Trying x.x.x.x:443...
* Connected to xx.execute-api.eu-north-1.amazonaws.com (x.x.x.x) port 443
* schannel: disabled automatic use of client certificate
* ALPN: curl offers http/1.1
* ALPN: server accepted http/1.1
* using HTTP/1.1
> GET /prod/GoalGroup HTTP/1.1
> Host: xx.execute-api.eu-north-1.amazonaws.com
> User-Agent: curl/8.4.0
> Accept: */*
>
* schannel: remote party requests renegotiation
* schannel: renegotiating SSL/TLS connection
* schannel: SSL/TLS connection renegotiated
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 9
< Connection: keep-alive
< Date: Sun, 31 Dec 2023 16:34:13 GMT
< x-amzn-RequestId: 62bf0657-8862-4ee0-8356-6fc28ab778b2
< Access-Control-Allow-Origin: https://dev.xy.amplifyapp.com/
< Access-Control-Allow-Headers: Content-Type
< x-amz-apigw-id: Q0SwqHDJgi0ErXA=
< Access-Control-Allow-Methods: OPTIONS, POST, GET, PUT, DELETE
< X-Amzn-Trace-Id: Root=1-65919803-5fa85b542d75331b23d71e5a;Sampled=0;lineage=86fad7fc:0
< X-Cache: Miss from cloudfront
< Via: 1.1 6f7e76153b6fdf51bfdb3e81126b917c.cloudfront.net (CloudFront)
< X-Amz-Cf-Pop: BUD50-P1
< X-Amz-Cf-Id: h4LtIHc1Nl9jQ7L1PPPbnpcRIuETaTvZB9-g0cEPPm--NT6hJce6nA==
<
"success"* Connection #0 to host xy.execute-api.eu-north-1.amazonaws.com left intact
有什么问题吗?
如何修复“无法获取”错误?
在标题的原始部分,我有一个像这样的结尾斜杠:
'Access-Control-Allow-Origin': 'https://dev.xy.amplifyapp.com/',
去掉多余的斜线后,就可以正常工作了。 谢谢你的提示。