简体   繁体   中英

How to make a cross domain request from javascript

 var http = new XMLHttpRequest(); var url = "http://example.com/"; http.crossDomain = true; http.withCredentials = true; http.open("GET", url, true); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.send(); console.log(http.responseText); 

When i try to do a cross domain request from the javascript as seen in the code, it throws me an error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:8000 ' is therefore not allowed access. How can i resolve that since i don't to persue solution of JSONP. Are there any other solutions from which i can resolve it. And i don't have control on the server side since its a third party server.

There is no way to read the data using purely client side code.

You need to make the request from a server, and have the client side code fetch the data from that server.

Said server will either be the same origin as the page hosting the JS or it will be one that uses CORS to grant permission to your origin.

The problem is that this request is thrown by the client rather than the server. One way to solve this is to use a proxy, eg a PHP proxy, so that you actually retrieve the data via a server script (for instance using cURL ) and make your JS script request your server page instead of the cross-server one.

PHP web proxies already exist, and looking here or here might give you an idea on how to achieve what you're looking for.

There is no way to make it using JS only, apart from asking the other server's owner to whitelist you, which in most cases is really unlikely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM