Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Dec 7, 2021

Avoid CORS issues in Chrome, Firefox, Safari and Edge for local JavaScript development

Setup a simple proxy using nodejs and npm to bypass CORS issues. 

This will solve the following issue in the web browsers:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disable

Install the following npm package globally:
npm install -g local-cors-proxy

Now you are ready to setup a local proxy. Let's say the URL that's throwing the CORS issue is: 
https://www.example.com/v1/api

To start the proxy, execute the following command:
lcp --proxyUrl https://www.example.com

You will get the following output:

Note: Do not close this window as long as you need the proxy.

Now, in the JavaScript code, API endpoint will be:
http://localhost:8010/proxy/v1/api

This will make a request to URL: https://www.example.com/v1/api without any issues.

Additional options to setup the proxy: 

Option Example Default
--proxyUrl https://www.google.ie
--proxyPartial foo proxy
--port 8010 8010
--credentials (no value needed) false
--origin http://localhost:4200 *

Original article can be viewed here.

Apr 17, 2018

Random ID / Text generator in Java Script

To generate random ids in JS use the following code:

Math.random().toString(36).substr(2, 9)

The length of the item can be increased/decreased by changing the value in functions toString(36) and substr(2, 9). 

Nov 14, 2011

Call a client side javascript method after a specific update panel has been loaded

<script type="text/javascript"> 
    $(document).ready(function() { 
    panelsLoaded = 1;
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(PageLoaded) }); 

    function PageLoaded(sender, args) { 
        console.log("I have occured " + panelsLoaded++ + " times!"); 
        var panelsCreated = args.get_panelsCreated(); 
        for (var i = 0; i < panelsCreated.length; i++) 
        { 
            console.log("Panels Updating: " + panelsCreated[i].id); 
        } 
        var panelsUpdated = args.get_panelsUpdated(); 
        for (var i = 0; i < panelsUpdated.length; i++) 
        { 
            console.log("Panels Updating: " + panelsUpdated[i].id);
        }
    } 
</script>

Just add all the scripts in the PageLoaded() function.