Ошибка failed to execute send on xmlhttprequest

I’m trying to do a POST ajax request to a server hosted locally on my laptop but I can’t seem to get any information back. When I click a button on my site (localhost), I can see the server passing back the correct information but on the front end I get this error:

error: NetworkError: Failed to execute ‘send’ on ‘XMLHttpRequest’: Failed to load ‘http://comp-ip’.

var param = JSON.stringify({varA:"varA",varB:"varB"});

$.ajax({
  type: "POST", 
  url: "http://comp-ip",
  async: false, 
  data: param,
  success: function(result, status, xhr){
    alert(result + ": " + status);
  },
  error: function(xhr, status, err) {
    alert(status + ": " + err);
  }
});

It seems to be triggering an error every time and not ‘success’. Anyone have any idea what is wrong?

Edit: I’ve tried sending a normal POST request without AJAX and it throws me an ‘undefined’ error as well:

$(document).ready(function(){
    var param = JSON.stringify({varA:"varA",varB:"varB"});
     $("#btn").click(function(event){
           $.post( 
              "http://ip",
               param,
               function(data) {
                 $('#container').html(data);
               }
           ).fail(function(error) { alert(error.responseJSON) });
        });
});

Other things I’ve tried:
1) Changing browsers to Safari (same thing, server returns information but the site gets an error)
2) Setting async = true from false. For some reason when I set it to true, the server doesn’t respond at all. When it’s false the server responds.

@redroot — Thanks for looking into this. There are a few different types of request involved here, so I don’t think what you’re seeing is necessarily related to what the other users were seeing, but it’s relevant.

First, calling variation doesn’t do any I/O at all; the method is synchronous in that it returns a value right away without deferring any actions, not because it performs a synchronous HTTP request (or any request).

Requests to events.launchdarkly.com are for posting analytics events (such as the ones generated by variation). That normally happens in an asynchronous flush task that is triggered by setTimeout, and the request itself is also async.

What you’re seeing is a special case. There is a beforeunload handler that is called whenever the current page is about to go away. It checks if there are any events waiting to be sent (i.e. if the flush task has not yet fired), and if so, it attempts to send them using a synchronous HTTP request (if it were async, it would have no chance to complete before the page got unloaded). All versions of ldclient-js have this. The intention is to minimize any loss of analytics events, so that your dashboard is as up to date as possible, without requiring you to use a very short event flush interval.

We suspected that browsers might stop supporting this kind of thing at some point, but we hadn’t seen this specific change in Chrome, so thanks for that. We’ll have to think about the best way to adapt. As for why you were seeing it a little before, but now are seeing it a lot, I would guess that either more of your users have the latest Chromium now, or for whatever reason your application is generating events more often than it used to so it’s more likely to have some unsent ones in the queue at page unload time.

The reason I doubt that the other comments had the same cause is that they didn’t include the «Synchronous XHR in page dismissal» message; I’m assuming they didn’t just forget to copy that, since it’s pretty distinctive.

Answer by Reginald Harrington

XMLHttpRequest cannot load
file:///C:/Users/hp/Downloads/single-page-app-angularjs-master/home.html.
Cross origin requests are only supported for protocol schemes: http,
data, chrome, chrome-extension, https, chrome-extension-resource.,Error: Failed to execute ‘send’ on ‘XMLHttpRequest’: Failed to load
‘file:///C:/Users/hp/Downloads/single-page-app-angularjs-master/home.html’.
XMLHttpRequest cannot load
file:///C:/Users/hp/Downloads/single-page-app-angularjs-master/about.html.
Cross origin requests are only supported for protocol schemes: http,
data, chrome, chrome-extension, https, chrome-extension-resource.,Error: [$compile:tpload]
http://errors.angularjs.org/1.3.3/$compile/tpload?p0=home.html,

1

Typically, Ajax isn’t supported when using file://. You’ll want to serve and access the page through an HTTP server. Note: http static server one-liners

– Jonathan Lonowski

Mar 8 ’15 at 4:08

On Windows:

chrome.exe --allow-file-access-from-files

or

chrome.exe --allow-file-access-from-files --disable-web-security

On Mac:

open /Applications/Google Chrome.app/ --args --allow-file-access-from-files

Answer by Sean Rollins

I’m very new to Angular SPA and for the first time I get a code by Googling and try to run. But I get some errors in Console. I couldn’t figure out why, I found list of following Console errors:,I got my problem. It should be helpful for another user for save the image and compress the image using javascript(AnguarJs). ,Here are some links to help point you in the right direction. If you don’t want to use any frameworks (Angular, Backbone, etc.) these links will be good. They use jQuery and perhaps one other library/plugin. Hope they help!,Now index.html is used as «master page» or «layout» if you are familiar with asp.net. When you clicking at the link, content of the templateUrl file is inserting into placeholder div.

XMLHttpRequest cannot load
file:///C:/Users/hp/Downloads/single-page-app-angularjs-master/home.html.
Cross origin requests are only supported for protocol schemes: http,
data, chrome, chrome-extension, https, chrome-extension-resource.

Error: Failed to execute ‘send’ on ‘XMLHttpRequest’: Failed to load
‘file:///C:/Users/hp/Downloads/single-page-app-angularjs-master/home.html’.
XMLHttpRequest cannot load
file:///C:/Users/hp/Downloads/single-page-app-angularjs-master/about.html.
Cross origin requests are only supported for protocol schemes: http,
data, chrome, chrome-extension, https, chrome-extension-resource.

Error: [$compile:tpload]
http://errors.angularjs.org/1.3.3/$compile/tpload?p0=home.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Single page web app using Angularjs</title>


<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
 <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
  <script src="script.js"></script>


</head>
<body ng-app="single-page-app">
  <div ng-controller="cfgController">
  <div>
  <nav class="navbar navbar-inverse" role="navigation" style="padding-left:130px;">
         <ul class="nav navbar-nav">
        <li class="active"><a href="#/">Home<span class="sr-only">(current)</span></a></li>
        <li><a href="#/about">About us</a></li>
        <li><a href="#/about">Read tutorial</a></li>
      </ul>
</nav>
</div>
  <br/>

  <div ng-view class="jumbotron"></div>
  </div>
</body>
</html>

Answer by Frankie Moran

Сообщение об ошибке {readyState:0,status:0,statusText:NetworkError: не удалось выполнить ‘send’ на ‘XMLHttpRequest’: не удалось загрузить… Когда выполняется следующее $.ajax({ url:…

ошибка: NetworkError: не удалось выполнить ‘send’ на ‘XMLHttpRequest’: не удалось загрузить ‘ http://comp-ip ‘.

var param = JSON.stringify({varA:"varA",varB:"varB"});

$.ajax({
  type: "POST", 
  url: "http://comp-ip",
  async: false, 
  data: param,
  success: function(result, status, xhr){
    alert(result + ": " + status);
  },
  error: function(xhr, status, err) {
    alert(status + ": " + err);
  }
});

Edit: я пытался отправить обычный запрос POST без AJAX, и он также выдает мне ошибку ‘undefined’:

$(document).ready(function(){
    var param = JSON.stringify({varA:"varA",varB:"varB"});
     $("#btn").click(function(event){
           $.post( 
              "http://ip",
               param,
               function(data) {
                 $('#container').html(data);
               }
           ).fail(function(error) { alert(error.responseJSON) });
        });
});

Answer by Lia Hahn

Following this I end up with the error Failed: Failed to execute ‘send’ on ‘XMLHttpRequest’: Failed to load ‘ng:///DynamicTestModule/module.ngfactory.js’.,https://stackoverflow.com/questions/44254758/angular-2-unit-testing-getting-error-failed-to-load-ng-dynamictestmodule-m,Sometimes even that doesn’t work and you need to set a breakpoint just before the exception and execute on the browser console and you receive the real error

import { Component } from '@angular/core';
import { WelcomeSegmentComponent } from '../../components/welcome-segment/welcome-segment';

@Component({
  selector: 'page-home',
  templateUrl: './home.html',
})

export class HomePage {

  constructor() {}

  ionViewDidLoad() {

  }

}


Has this ever happened to you? You’re working on the code for your Angular app. And since you’re an amazing developer, you’re also writing test specs using Jasmine. You want to run your tests so you pop down to the terminal and type ng test to execute your tests.

You expect to have everything run and pass but instead you get a half-zillion test failures and lots of them have a weird and completely unhelpful error message:

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest'

Bad Karma: Tons of failed test specs with the XMLHttpRequest error

WHAT — IS — GOING — ON?!?!?!?!

It’s Not the Real Error

The problem here is that the real error message is hidden. I don’t remember where I learned this trick but it’s helped me out a bunch of times in my Jasmine tests for Angular.

Instead of running your tests with the ng test command, use ng test --source-map=false.

The Real Error Revealed

Ok. So this time, you head to the command prompt (shell, terminal, etc) and you run ng test --source-map=false.

This time you’ll get a much better error. In this case, the error message is «NullInjectorError: R3InjectorError(DynamicTestModule)[FormBuilder -> FormBuilder]: NullInjectorError: No provider for FormBuilder!«

A much better error message

It’s Almost Always a Dependency Problem

The underlying problem is almost always some kind of missing dependency that’s causing the Angular dependency injection / IoC framework to panic.

So when our typescript or javascript code gets executed, it goes through something like a compilation process that take the human-readable code and turns it into something that can be executed efficiently. In the case of typescript, there’s an extra step and the code gets ‘transpiled’ into javascript before execution. The source map is supposed to help us to debug our code by connecting the instructions that are being executed to the source code that inspired those instructions. If we didn’t have that, it would be a whole lot harder to debug our apps.

My theory on why ng test –source-map=false helps in these weirdo error cases is that because of the type of problem (dependency injection problems), the source map thinks that the problem is in the dependency injection framework rather than in your code that configures the dependencies.

So. By turning off the source map generation, you get the real error.

(Disclaimer: that theory could be wildly wrong…but it makes sense to me.)

A Little More About My Error

So this blog post is about how to get at the real error message but while I’m here, I figure I might as well tell you how I fixed the real error, too. Like I said, it’s almost always a dependency problem. Lately, I’ve been working on converting a bunch of template-driven angular forms over to reactive forms. This means that in my Jasmine specs, that I need to update the imports directive to reference ReactiveFormsModule instead of FormsModule.

To fix this, I need to get to the call to TestBed.configureTestingModule and find the FormsModule import. Change this over to be ReactiveFormsModule and voila! — the problem is fixed.

The import for FormsModule that needs to be modified

Change the import to ReactiveFormsModule

Summary

In short, there’s something about dependency import problems in Jasmine tests for Angular that sometimes causes the real errors to be eaten. So if you find yourself wondering about why you’re getting that strange XMLHttpRequest error, try running your test suite without source maps. The command to do that is ng test --source-map=false.

I hope this helps.

-Ben

— Looking for help with Angular and/or Angular testing? We can help. Drop us a line at info@benday.com.

In the process of developing the project, and the back-end docking, we use a mature integrated and comprehensive architecture JHipster. The back end is java spring-boot front end ts+react, and the requirement is that there is a requirement to nest an iframe in the page. Then an error occurred in the front end of the $.ajax request initiated in the iframe as follows:

"NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://192.168.31.149:8081/api/concepts/3253'

Front-end code:

$.ajax({
  url: `$ {RED.API.schema.URI ()} / $ {conceptIds}`,
  method: "GET",
  async: false,
  crossDomain: true,
  headers: {
  'Access-Control-Allow-Origin': '*',
  accept: 'application/json',
  Authorization: `Bearer ${window.parent.localStorage
    .getItem("jhi-authenticationToken")
    .replace(/"/g, "")}`,
  },
  success: data => {
    console.log(data)
  },
  error: err => {
    console.error(err)
  },
});

As you can see, as long as the $.ajax request opens and closes async to open the synchronous mode, the data cannot be requested.

Solution:

After consulting, some information on the Internet. I found that most of the solutions are just to change async to true. But my project application must use synchronization to render data. So it can’t be changed to asynchronous use.

Finally, use docker to run two containers to simulate the online and local environments respectively. The following differences are found in the request header of the request:

After local debugging, the difference between the request response of the static file proxy mode and the local development mode is found as follows: 
[Online Response Headers] 
Accept-Ranges: bytes 
Cache-Control: no-store 
Connection: keep-alive 
Content-Encoding: gzip 
Content-Language: en- 
Content-Length: 2213 
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: 
Content-Type: text/html;charset=utf-8 
Date: Thu, 18 Jul 2019 06:28:37 GMT 
Feature-Policy: geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none' 
Last-Modified: Thu, 18 Jul 2019 02:03:28 GMT 
Referrer-Policy: strict-origin-when-cross-origin 
Server: nginx/1.17.0 
X-Content-Type-Options: nosniff 
X-Frame-Options: DENY 
X-XSS-Protection: 1; mode=block 


[Local Response Headers] 
accept-ranges: bytes 
Connection: keep-alive 
Content-Type: text/html; charset=UTF-8 
Date: Thu, 18 Jul 2019 06:40:59 GMT 
etag: W/"16de-hwm87recU2tkzw2pAE/RFVGX6+0" 
Server: nginx/1.17.0 
Transfer-Encoding: chunked 
x-powered-by: Express 

[Comparative difference] 
There are more settings online: 
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: 
Feature-Policy: geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none' 
Referrer-Policy: strict-origin-when-cross-origin 
X-Content-Type-Options: nosniff 
X-Frame-Options: DENY 
X-XSS-Protection: 1; mode=block

The result is that the back-end of the framework is configured with an xss security mechanism called Content-Security-Policy to intercept insecure requests. Then comment in config/SecurityConfiguration.java in the java project and remove the injection of the response header to solve the problem.

// SecurityConfiguration.java

@Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .csrf()
            .disable()
            .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
            .exceptionHandling()
            .authenticationEntryPoint(problemSupport)
            .accessDeniedHandler(problemSupport)
        .and()
            // .headers()
            // .contentSecurityPolicy("default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:")
        // .and()
            // .referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
        // .and()
            // .featurePolicy("geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'")
        // .and()
            // .frameOptions()
            // .sameOrigin()
        // .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .authorizeRequests()
            .antMatchers("/api/authenticate").permitAll()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/activate").permitAll()
            .antMatchers("/api/account/reset-password/init").permitAll()
            .antMatchers("/api/account/reset-password/finish").permitAll()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/info").permitAll()
            .antMatchers("/management/prometheus").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
        .and()
            .httpBasic()
        .and()
            .apply(securityConfigurerAdapter());
        // @formatter:on
    }

Similar Posts:

Понравилась статья? Поделить с друзьями:
  • Ошибка failed to establish connection
  • Ошибка failed to erase block
  • Ошибка failed to download the vs2013 redistributable
  • Ошибка failed to download metadata for repo appstream
  • Ошибка failed to creates process