Skip to content

Commit 284c443

Browse files
author
David Brown
committed
add origin header check to CORS function
1 parent 8af1b1b commit 284c443

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

add-cors-header/index.js

+11-9
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
function handler(event) {
1+
function handler(event) {
22
var request = event.request;
3-
var headers = request.headers;
4-
var host = request.headers.host.value;
5-
6-
// If origin header is missing, set it equal to the host header.
7-
if (!headers.origin)
8-
headers.origin = {value:`https://${host}`};
9-
10-
return request;
3+
var response = event.response;
4+
5+
// If Access-Control-Allow-Origin CORS header is missing, add it.
6+
// Since JavaScript doesn't allow for hyphens in variable names, we use the dict["key"] notation.
7+
if (!response.headers['access-control-allow-origin'] && request.headers['origin']) {
8+
headers['access-control-allow-origin'] = {value: request.headers['origin'].value};
9+
console.log("Access-Control-Allow-Origin was missing, adding it now.");
10+
}
11+
12+
return response;
1113
}

add-cors-header/test-objects/no-cors-header.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
},
1616
"headers": {
1717
"host": { "value": "www.example.com" },
18-
"accept": { "value": "text/html", "multivalue": [ { "value": "text/html" }, { "value": "application/xhtml+xml" } ] }
18+
"accept": { "value": "text/html", "multivalue": [ { "value": "text/html" }, { "value": "application/xhtml+xml" } ] },
19+
"origin": { "value": "https://www.example.com"}
1920
},
2021
"cookies": {
2122
"id": { "value": "CookeIdValue" },

0 commit comments

Comments
 (0)