Access response headers in HTTP Fetch API with Serverless Framework and AWS Lambda
In order to access response headers such as Location in HTTP Fetch api whilst using Serverless Framework and AWS Lambda Functions with CORS enabled, you need to do the following.
Make sure cors is set to true on serverless.yml
postUsers:
handler: handler.postUsers
events:
- http:
path: users
method: post
cors: trueMake sure in the response header, you are returning the following:
callback(null, {
statusCode: 201,
headers: {
"Access-Control-Allow-Origin": "*",
// Required for cookies, authorization headers with HTTPS
"access-control-allow-credentials": true,
"access-control-allow-headers": "Location",
"access-control-expose-headers": "Location",
Location: id
}
});Now, you can access the header location from fetch.
this.httpClient
.fetch("/users", {
method: "post",
body: json({ username: "chekkan" })
})
.then(res => {
return res.headers.get("location");
});References: