在开发项目的过程中,和后端对接,我们使用是一个成熟的集成很全面的架构JHipster。后端为java spring-boot 前端ts+react,需求是有一个需要在页面里嵌套iframe的需求。然后在iframe中发起$.ajax请求前端出现了错误如下:

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

前端代码:

$.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)
},
});

可以看到,只要$.ajax请求打开关闭async开启同步模式则就会无法请求数据。

解决方法:

经过查阅,网上的一些信息。发现大部分解决方案都是吧async改为true就可以了。但我的项目运用里必须使用同步来渲染数据。所以没法改成异步使用。

最后使用docker跑两个容器分别模拟线上和本地的环境。发现请求的请求头里有着如下差异:

经过本地调试,找到静态文件代理模式和本地开发模式的请求响应差异如下:
【线上的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 【本地的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 【对比差异】
线上的多了一下设置:
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

结果是该框架的后端配置了一种叫Content-Security-Policy的xss安全机制,拦截的不安全的请求。随后在java项目里config/SecurityConfiguration.java 注释去掉该响应头的注入即解决问题。

// 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
}

NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load xxxx错误解决方法的更多相关文章

  1. mui.min.js:7 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load

    mui框架做的微信公众号网页,在上传数据的时候报了这个错,async: true,//将false改为true就可以了 https://blog.csdn.net/liuzp111/article/d ...

  2. 配置Chrome启动参数支持本地AJAX请求,解决XMLHttpRequest cannot load file..,Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest':.. 问题

    直接将本地的HTML文件拖拽到Chrome浏览器中运行时,发送的AJAX请求本地文件,会报跨域错误: 报错的原因是:Chrome默认不支持本地的AJAX请求! 解决问题的办法是:给Chrome浏览器添 ...

  3. [Vue warn]: Failed to mount component: template or render function not defined. 错误解决方法

    解决方法import Vue from "vue"; 默认引入的文件是 vue/dist/vue.runtime.common.js.这个可以在node_modules/vue/p ...

  4. Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.

    在设置请求头的时候报这个Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPE ...

  5. vue 运行项目时,Uncaught (in promise) DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL

    npm  run dev 运行项目后 验证码显示不出来 并报错 Uncaught (in promise) DOMException: Failed to execute 'open' on 'XML ...

  6. WebRTC | Failed to execute 'setLocalDescription' on 'RTCPeerConnection': Failed to parse SessionDescription. a=msid: Missing track ID in msid attribute.

    1.问题回放 使用如下代码获取局域网IP报错 (代码来源:https://github.com/diafygi/webrtc-ips 日期:2019-02-16) Uncaught (in promi ...

  7. javamail发送邮件及错误解决方法javax.mail.AuthenticationFailedException: failed to connect, no password specified?

    javamail发送邮件及错误解决方法javax.mail.AuthenticationFailedException: failed to connect, no password specifie ...

  8. Failed dependencies: 检查依赖性错误 解决方法

    centOs下: error: Failed dependencies: 检查依赖性错误 解决方法 刚才安装avast的linux版,结果出现了: [root@localhost /]# rpm -i ...

  9. PHP failed to ptrace(PEEKDATA) pid 13659: Input/output error错误解决方法

    PHP failed to ptrace(PEEKDATA) pid 13659: Input/output error错误解决方法 现在改linux内核文件打开限制<pre>ulimit ...

随机推荐

  1. BGP的一网双平面规划

    网络拓扑: XRV1 ===================================================================== # sysname XRV1# boa ...

  2. Win10《芒果TV》更新v3.5.2星玥版:修复电视台直播异常,优化添加下载提示

    Win10版<芒果TV>在更新夏至版之后,根据收集到的热心用户反馈,全平台同步更新星玥版v3.5.2,修复电视台直播异常,优化添加下载提示,进一步提升使用体验. Win10版<芒果T ...

  3. SQLServer 复制中移除和添加发布而不初始化所有项目

    原文:SQLServer 复制中移除和添加发布而不初始化所有项目 -- 若提前"禁止架构更改",新增的列不会自动添加大发布,此时应使用 sp_articlecolumn 添加列 E ...

  4. LINQ查询表达式---------orderby子句

    LINQ查询表达式---------orderby子句 LINQ可以按元素的一个或多个属性对元素进行排序. class Program { public class PerInfo { public ...

  5. C# Excel导入Access

    /// <summary> /// 导入 /// </summary> private void btn_In_Click(object sender, EventArgs e ...

  6. C# WebRequest POST上传数据

    WebRequest request = WebRequest.Create("http://www.cnsos.net"); // Set the Method property ...

  7. Android零基础入门第45节:GridView简单使用

    原文:Android零基础入门第45节:GridView简单使用 前面一共用了8期来学习ListView列表的相关操作,其实学习的ListView的知识完全适用于AdapterView的其他子类,如G ...

  8. Docker+ Kubernetes已成为云计算的主流(二十五)

    前言 最近正在抽时间编写k8s的相关教程,很是费时,等相关内容初步完成后,再和大家分享.对于k8s,还是上云更为简单.稳定并且节省成本,因此我们需要对主流云服务的容器服务进行了解,以便更好地应用于生产 ...

  9. webstrom sass 关于arguments 和 Output paths to refresh 设置

    第一种设置: Arguments:--no-cache --update -t expanded $FileName$:$FileNameWithoutExtension$.css Output pa ...

  10. Dynamics 365 for sales - Account与Contact之间的关系

    Account :可以理解成客户,可以是公司组织,当然也可以是个人 Contact: 从字面理解为联系人 例如,腾讯公司要买我们公司的软件,他们的主要负责人是IT部门的小马,那么,腾讯要创建成Acco ...