Php xmlhttprequest cannot load

JavaScript — XMLHttpRequest не может загрузить и Uncaught NetworkError

Я работаю над клиентским проектом с jquery и javascript, а также использую плагины jquery. Наш профессор предоставил нам файл proxy.php для получения данных, необходимых для запуска веб-приложения. Я использовал плагин easy tab, который импортировал файл jquery.min.js. Но я получаю сообщение об ошибке, и файл proxy.php не загружается.

 else < $url=HOSTNAME.$_GET['path']; $session = curl_init($url); curl_setopt($session, CURLOPT_HEADER, false); curl_setopt($session, CURLOPT_RETURNTRANSFER, true); >$xml = curl_exec($session); header("Content-Type: text/xml"); echo $xml; curl_close($session); ?> 

Это ошибки, которые я продолжаю получать. Как это исправить?

 XMLHttpRequest cannot load file:///C:/Users/Kubra/Desktop/Project2/proxy.php ?path=%2FCities%3Fstate%3DNY&_=1429379822193. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. jquery.min.js:6 Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/Users/Kubra/Desktop/Project2 /proxy.php? path=%2FCities%3Fstate%3DNY&_=1429379822193'. 

Решение

Вы не можете использовать XMLHttpRequest для загрузки вещей из локальной файловой системы.

Вы должны разместить свой сайт на реальном веб-сервере.

Смотрите этот ответ для получения дополнительной информации: xmlhttprequest для локальных файлов

Другие решения

Источник

Why I am getting XMLHttpRequest cannot load — Preflight response is not successful Error with Delete method only?

The get method is working and return results but it doesn’t work with delete method. If it’s because of CORS, then why the get method is working? Console Log: enter image description here Network: enter image description here Related Questions: “XMLHttpRequest cannot load file:///… Preflight response is not successful” error Preflight response is not successful Express server and Axios CORS Preflight response is not successful

is the problem persisting with your modification on Access-Control-Allow-Methods header? (developer.mozilla.org/en-US/docs/Web/HTTP/Headers/…)

@PierreMallet not sure what is causing the problem. I have included all the methods in the Access-Control-Allow-Methods but it only works with GET not DELETE.

1 Answer 1

Ok, I think it is because if the method is different from GET or DELETE you return a 404. So when the preflight request is handled ( verb OPTIONS ) you return a 404.

Here is an example of CORS in PHP (here)

The important point here is that the API script needs to recognise when an initial OPTIONS request has been received, and to return the appropriate access control headers in that case (and nothing more). Following this, the browser then initiates a second request in which the real work is done.

In your specific case I think the code should be :

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')

If you want to enable the cors more globally you can just add

header('Access-Control-Allow-Origin: *'); 

Источник

Читайте также:  Python games in browser

CORS CSFR XMLHttpRequest cannot load

I work on a third party web based application, lets call it Po, by injecting company required modifications via JQuery which calls PHP code in a digital workplace type domain of ours https://digitalworkplace.staging.c.com The digital workplace code then calls our API, using CURL and POST, which is on a different domain of ours, http://p.staging.c.com This was previously all working fine until Po added in CSFR support on each of their application pages. I get the CSRF token from the Po page where it is hidden in a field with , name=»CSRF_NONCE» I make the AJAX call with the following settings:

$.ajaxSetup( < headers: < 'Content-Type': 'application/json; charset=UTF-8', 'CSRF_NONCE' : csrf >>); $.ajaxPrefilter(function(options) < options.beforeSend = function(xhr)< xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhr.setRequestHeader('CSRF_NONCE', csrf); >>); $.ajax(< type: "POST", accept: 'application/json', crossOrigin: true, crossDomain: true, method: m, beforeSend: function(xhr)< xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhr.setRequestHeader('CSRF_NONCE', csrf); >, url: u, data: d, dataType: "json", contentType: "application/json", swotId: s, async: a, headers: < "Content-Type": "application/json; charset=UTF-8", "CSRF_NONCE": csrf, >, xhrFields: < withCredentials: true >, success: function(xhr) < console.log("yippee"); >, error: function(e) < console.log(e); >>); 
Request URL:https://digitalworkplace.staging.c.com/web/p/versio/mysql/getmasterordernumber Request Method:OPTIONS Status Code:200 OK Remote Address:192.168.253.11:443 
Allow:OPTIONS, TRACE, GET, HEAD, POST Content-Length:0 Date:Mon, 27 Mar 2017 11:09:45 GMT Public:OPTIONS, TRACE, GET, HEAD, POST Server:Microsoft-IIS/8.5 

This looks like IIS 8.5 is responding to the preflight request. To try and prevent this in IIS I have added into web.config the following:

It seems to me that something is wrong with the IIS setup. In Chrome I can see the POST request header as below but then no response.

Accept:*/* Accept-Encoding:gzip, deflate, sdch, br Accept-Language:en-GB,en-US;q=0.8,en;q=0.6 Access-Control-Request-Headers:access-control-allow-headers, access-control-allow-methods, access-control-allow-origin, content-type, csrf_nonce Access-Control-Request-Method:POST Connection:keep-alive Host:digitalworkplace.staging.c.com Origin:http://p.staging.c.com Referer:http://p.staging.c.com/pagesUTF8/auftrag_allgemeinauftrag.jsp?OSG08=24370 User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 

Does anyone have any suggestion of what else I need to do to allow the POST request to function after the preflight?

Источник

XMLHttpRequest cannot load

enter image description here

I am trying to integrate Open Weather API in my website, for this I have written some coding and it’s working as expected in my local system. The same code is not working in Live. it’s returning error and I have googled for this error and I tried so many examples like xml json XMLHttpRequest jsonp But all examples is working locally when Live it’s not working. Throwing same error as below. For above I have tried below code: Example 1

   
  

In Example 2 I have tried both xml , json and jsonp Mode in url and datatype. But again throwing same Error. Could you please suggest me how to do it.

Читайте также:  Css for table class

Источник

XMLHttpRequest cannot load. Origin is not allowed by Access-Control-Allow-Origin

This is happening because of the CORS (Cross Origin Resource Sharing) error. A request for a resource (like an image or a font) outside of the origin is known as a Cross-Origin Request. Cross Origin Resource Sharing (CORS) manages cross-origin requests. For example, if you are doing something like writing HTML and Javascript in a code editor on your personal computer, and testing the output in your browser, you might probably get error messages about Cross Origin Requests . You cannot issue requests through the XMLHttpRequest to other domains or subdomains.

JSONP (JSON with Padding)

xmlhttprequest cannot load is not allowed by access-control-allow-origin

JSONP ( JSON with Padding ) is a method commonly used to bypass the cross-domain policies in web browsers. You’re on domain example.com , and you want to make a request to domain example.net . To do so, you need to cross domain boundaries. JSONP is really a simple trick to overcome the XMLHttpRequest same domain policy. So, instead of using XMLHttpRequest we have to use HTML tags, the ones you usually use to load JavaScript files , in order for JavaScript to get data from another domain.

JSONP requests are not dispatched using the XMLHTTPRequest and the associated browser methods. Instead a tag is created, whose source is set to the target URL . This script tag is then added to the DOM (normally inside the element).

JSONP Request:

var tag = document.createElement(«script»); tag.src = ‘somewhere_else.php?callback=foo’; document.getElementsByTagName(«head»)[0].appendChild(tag);

Here you can see the JSONP response object is passed as an argument to a callback function.

This is why you see JSONP requests containing the callback parameter, so that the server knows the name of the function to wrap the response. This function must exist in the global scope at the time the tag is evaluated by the browser (once the request has completed). The following assumes a response object < "bar" : "baz" >.

function foo(response) < document.getElementById("output").innerHTML = response.bar; >; var tag = document.createElement(«script»); tag.src = ‘somewhere_else.php?callback=foo’; document.getElementsByTagName(«head»)[0].appendChild(tag);

That’s all there is to know about JSONP : it’s a callback and script tags.

xmlhttprequest cannot load due to access control

Since JSONP ( JSON with Padding ) works by appending a element to load the data in the form of a JavaScript program which calls a function already in the page, attempting to use the JSONP technique on a URL which returns JSON will fail — typically with a CORS error — because JSON is not JavaScript.

Local Development (Chrome)

In simple words, this error occurs when we try to access a domain/resource from another domain. If this is for local development and you are using Chrome , you need to run Chrome with a couple of arguments to relax security like this:

Читайте также:  Плагин воскрешения игроков css v34

«C:\Program Files (x86)\Google\Chrome\Application\chrome.exe» —allow-file-access-from-files —disable-web-security

Localhost

If you need to enable CORS on the server in case of localhost, you need to have the following on request header.

xmlhttprequest cannot load access control checks

Using Proxy

The other easy way out, would be to create a proxy on your local server, which gets the remote request and then just forwards it back to your javascript.

Browser extensions

Cross Origin Resource Sharing ( CORS ) is blocked in modern browsers by default (in JavaScript APIs). It is possible for a browser extension to inject the CORS headers in the response before the Same Origin Policy (SOP) is applied. These can be useful for development, but are not practical for a production site.

Cross-Origin Resource Sharing (CORS)

CORS is a mechanism by which data or any other resource of a site could be shared intentionally to a third party website when there is a need. It uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. It extends and adds flexibility to the same-origin policy (SOP). However, it also provides potential for cross-domain based attacks, if a website’s CORS policy is poorly configured and implemented.

Same-Origin Policy (SOP)

The SOP ( same-origin policy ) is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin. A browser can load and display resources from multiple web-sites at once. You might have multiple tabs open at the same time, or a web-site could embed multiple iframes from different sites. If there is no restriction on interactions between these resources, and a script is compromised by an attacker, the script could expose everything in a user’s browser. The SOP prevents this from happening by blocking read access to resources loaded from a different origin .

Same-Origin Policy ( SOP ) is supported by effectively all modern browsers. It is a rule enforced by web browsers, which controls access to data between websites and web applications . An origin is defined by the scheme, host, and port of a URL. It is a browser security feature that restricts how documents and scripts on one origin can interact with resources on another origin. Without this policy , any web page would be able to access the Document Object Model (DOM) of other pages. This would let it access potentially sensitive data from another web page as well as perform actions on other web pages without user consent.

Источник

Оцените статью