10 examples of 'fetch cors' in JavaScript

Every line of 'fetch cors' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
3function fetchNoCors(url, isOpaqueFiltered) {
4 var urlQuery = "?pipe=header(x-is-filtered,value)"
5 promise_test(function(test) {
6 if (isOpaqueFiltered)
7 return fetch(url + urlQuery, {"mode": "no-cors"}).then(function(resp) {
8 assert_equals(resp.status, 0, "Opaque filter: status is 0");
9 assert_equals(resp.statusText, "", "Opaque filter: statusText is \"\"");
10 assert_equals(resp.url, "", "Opaque filter: url is \"\"");
11 assert_equals(resp.type , "opaque", "Opaque filter: response's type is opaque");
12 assert_equals(resp.headers.get("x-is-filtered"), null, "Header x-is-filtered is filtered");
13 });
14 else
15 return fetch(url + urlQuery, {"mode": "no-cors"}).then(function(resp) {
16 assert_equals(resp.status, 200, "HTTP status is 200");
17 assert_equals(resp.type , "basic", "Response's type is basic");
18 assert_equals(resp.headers.get("x-is-filtered"), "value", "Header x-is-filtered is not filtered");
19 });
20 }, "Fetch "+ url + " with no-cors mode");
21}
3export default function corsFetch(url, options) {
4 if (!options) options = {};
5
6 let isCancelled, actualResolve, actualReject;
7 let loadScript = null;
8 const name = 'callback' + (myIndex++);
9 window[name] = downloaded;
10 let cancelable = new Promise(download);
11 cancelable.cancel = cancel;
12
13
14 return cancelable;
15
16 function download(resolve, reject) {
17 actualResolve = resolve;
18 actualReject = reject;
19
20 loadScript = document.createElement('script');
21 loadScript.src = `${url}&callback=${name}`;
22 loadScript.onerror = reject;
23 document.head.appendChild(loadScript);
24 }
25
26 function cancel() {
27 isCancelled = true;
28 }
29
30 function downloaded(e) {
31 if (isCancelled) {
32 dispose();
33 return;
34 }
35
36 actualResolve(e);
37 dispose();
38 }
39
40 function dispose() {
41 if (loadScript) {
42 document.head.removeChild(loadScript);
43 loadScript = null;
44 }
45 delete window[name];
46 }
47}
77function setCors({whitelist = [], logger}) {
78 return cors({
79 origin(origin, callback) {
80 if (whitelist.indexOf(origin) !== -1 || !origin) {
81 callback(null, true);
82 } else {
83 logger.warn({origin, whitelist}, 'Rejected by CORS');
84 callback(new Error('Not allowed by CORS'));
85 }
86 },
87 credentials: true,
88 });
89}
31function makeCorsRequest() {
32 // This is a sample server that supports CORS.
33 var url = 'http://localhost:8080/api/v1/user/auth_session';
34
35 var xhr = createCORSRequest('GET', url);
36 if (!xhr) {
37 alert('CORS not supported');
38 return;
39 }
40
41 // Response handlers.
42 xhr.onload = function() {
43 var text = xhr.responseText;
44 var title = getTitle(text);
45 alert('Response from CORS request to ' + url + ': ' + title);
46 };
47
48 xhr.onerror = function() {
49 alert('Woops, there was an error making the request.');
50 };
51
52 xhr.send();
53}
121function configureCorsForBucket(aws, bucketName) {
122 const params = {
123 Bucket: bucketName,
124 CORSConfiguration: require('./resources/CORSPolicy')
125 };
126
127 return aws.request('S3', 'putBucketCors', params);
128}
60function setupCORS (api, path) {
61 api.paths[path].options = api.paths[path].options || cors
62}
158function setupCors(swaggerApp, remotes) {
159 var corsOptions = remotes.options && remotes.options.cors ||
160 { origin: true, credentials: true };
161
162 // TODO(bajtos) Skip CORS when remotes.options.cors === false
163 swaggerApp.use(cors(corsOptions));
164}
7module.exports = function fetch(obj, options) {
8 options = options || {};
9 options.parser = options.parser || httpResponseParser.parse;
10 var request = createCORSRequest(obj.type, obj.url, options);
11 if (!request) {
12 throw new Error('You cannot perform ajax request on other domains.');
13 }
14 return new Promise(function (success, failure) {
15 //Request error handler
16 request.onerror = function (error) {
17 failure(error);
18 };
19 //Request success handler
20 request.onload = function () {
21 var status = request.status;
22 if (status !== 200) {
23 var err = JSON.parse(request.response);
24 err.statusCode = status;
25 failure(err);
26 }
27 var contentType = request.getResponseHeader('content-type');
28 var data;
29 if (contentType && contentType.indexOf("application/json") !== -1) {
30 data = options.parser(request);
31 } else {
32 data = request.responseText;
33 }
34 success(data);
35 };
36 //Execute the request.
37 request.send(obj.data);
38 });
39
40};
34function handleCors0(req, res, allowDomains){
35 var route = req.route;
36 if(route.annotations.allowDomains === false){
37 sh.error("Cross origin request for " + req.url + " for which @allowDomains is false");
38 req.setFlag("abort", 403, "Forbidden");
39 return;
40 }
41 var origin = req.headers.origin ? req.headers.origin.toLowerCase() : "*";
42 var ok = false;
43 for(var i=0;i
22function createCORSRequest(method, url) {
23 var xhr = new XMLHttpRequest();
24
25 if (xhr.withCredentials != null) {
26 xhr.open(method, url, true);
27 } else if (typeof XDomainRequest !== "undefined") {
28 xhr = new XDomainRequest();
29 xhr.open(method, url);
30 } else {
31 xhr = null;
32 }
33
34 return xhr;
35};

Related snippets