首先,确保您的API Gateway正在使用基于令牌的身份验证。如果需要,您可以使用AWS Cognito将用户身份验证与API Gateway集成。
其次,确保您的Amplify配置正确设置,包括设置API Gateway终端节点和授权类型。例如:
Amplify.configure({
...
API: {
endpoints: [
{
name: "myEndpoint",
endpoint: "https://my-api-gateway-url.execute-api.us-east-1.amazonaws.com",
region: "us-east-1",
custom_header: async () => {
return {
Authorization: `Bearer ${(await Auth.currentSession()).getIdToken().getJwtToken()}`,
};
},
},
],
},
});
在get请求中使用fetchAuthSession:
import { API, Auth } from 'aws-amplify';
const makeAuthedRequest = async () => {
const session = await Auth.currentSession();
const apiKey = 'YOUR_API_KEY';
const apiName = 'myEndpoint';
const path = '/myresource';
const init = {
headers: {
'x-api-key': apiKey,
}
}
const apiResponse = await API.get(apiName, path, init);
return apiResponse;
}