HttpClient跨域请求

作者: IT飞牛 | 来源:发表于2018-07-23 17:25 被阅读0次

    下面是简单的http请求代码,这么直接如果直接运行:

    import { HttpClient } from '@angular/common/http';
    constructor(private http: HttpClient){
            this.http.get("http://www.abc.cn/upload/upload/1788.jpg").subscribe(value => {
            console.log(value)
          })
    }
    

    运行时,控制台报错:

    XMLHttpRequest cannot load http://www.abc.cn/upload/upload/1788.jpg. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
    

    方法一

    在浏览器属性中增加几行命令,即可解决该问题,具体做法如下:
    右击浏览器,选择属性,目标那一栏中增加如下命令:

     --args --disable-web-security --user-data-dir=C:\MyChromeDevUserData
    

    注意--args前面要保留空格,即可解决该问题。


    image.png

    然后在C盘创建目录:MyChromeDevUserData

    重新启动后,发现页面没有报错。

    方法二

    打开根目录下ionic.config.json,写入代理配置

    "proxies": [
        {
          "path": "/m/",
          "proxyUrl": "http://wanm.cn/m/"
        },
        {
          "path": "/m2/",
          "proxyUrl": "http://wanm.cn/m2/"
        }
      ]
    

    在想访问http://wanm.cn/m/xxx的时候,就改成访问/m/xxx,ionic会自动把以http://localhost:8000/m/开头的请求都转发到http://wanm.cn/m/xxx。重新启动就能生效。

    相关文章

      网友评论

        本文标题:HttpClient跨域请求

        本文链接:https://www.haomeiwen.com/subject/psbjmftx.html