Angular2的JSONP模块是否可以强制读取MIME类型('application/json')?
Can JSONP module of Angular 2 be forced to read MIME type ('application/json')?
我正在使用 JSONP 模块调用 SonarQube API。
this.jsonp.get('https://sonarqube.com/api/projects/index')
.subscribe(res => console.log(res));
之前使用了Angualar2的Http模块,导致浏览器报错
Origin http://localhost:4200 is not allowed by Access-Control-Allow-Origin
为了克服这个问题,我发现您可以使用 JSONP
或 CORS
或启动 chrome 和 --disable-web-security
,我可以找到足够的打字稿支持来获得以 JSONP 开头。但是我后来发现 JSONP expects MIME-type to be application/javascript 当我得到以下错误
Refused to execute script from 'https://sonarqube.com/api/projects/index' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
有没有办法强制JSONP模块获取JSON数据并成功解析?
解决方案 1:在服务器中启用 JSONP
我发现这是不可能的。 JSONP 只是克服 Cross-Origin-Requests problem
的一种方法,但它需要修改服务器 configuration/implementation 以提供 JSONP 数据 (MIME-type: application/javascript
)。
解决方案 2:在服务器中启用 CORS 支持
CORS
是 Cross-Origin-Requests 问题的最新解决方案。可以通过在服务器中添加以下headers来解决:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,PUT,DELETE
Access-Control-Allow-Headers: Authorization, Lang
解决方案 3:使用反向代理
我在搜索中遇到的一个建议是 使用服务器获取 Cross-Origin-Request。我无法控制服务器代码。然后我在 angular 论坛上遇到了 Reverse Proxies, found the cors-anywhere
包的概念。反向代理代表您的 front-end 获取这些资源,并将 CORS headers 添加到代理请求中。
我正在使用 JSONP 模块调用 SonarQube API。
this.jsonp.get('https://sonarqube.com/api/projects/index')
.subscribe(res => console.log(res));
之前使用了Angualar2的Http模块,导致浏览器报错
Origin http://localhost:4200 is not allowed by Access-Control-Allow-Origin
为了克服这个问题,我发现您可以使用 JSONP
或 CORS
或启动 chrome 和 --disable-web-security
,我可以找到足够的打字稿支持来获得以 JSONP 开头。但是我后来发现 JSONP expects MIME-type to be application/javascript 当我得到以下错误
Refused to execute script from 'https://sonarqube.com/api/projects/index' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
有没有办法强制JSONP模块获取JSON数据并成功解析?
解决方案 1:在服务器中启用 JSONP
我发现这是不可能的。 JSONP 只是克服 Cross-Origin-Requests problem
的一种方法,但它需要修改服务器 configuration/implementation 以提供 JSONP 数据 (MIME-type: application/javascript
)。
解决方案 2:在服务器中启用 CORS 支持
CORS
是 Cross-Origin-Requests 问题的最新解决方案。可以通过在服务器中添加以下headers来解决:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,PUT,DELETE
Access-Control-Allow-Headers: Authorization, Lang
解决方案 3:使用反向代理
我在搜索中遇到的一个建议是 使用服务器获取 Cross-Origin-Request。我无法控制服务器代码。然后我在 angular 论坛上遇到了 Reverse Proxies, found the cors-anywhere
包的概念。反向代理代表您的 front-end 获取这些资源,并将 CORS headers 添加到代理请求中。