美文网首页JavaScript 进阶营
服务器跨域问题解决办法

服务器跨域问题解决办法

作者: 桃子是水果 | 来源:发表于2019-12-18 16:56 被阅读0次

    创建proxy.conf.json配置文件,配置代理

    举例:angular运行在localhost:4200,需要访问地址在localhost:8080的api,apiurllocalhost:8080/api/user/,那么配置如下即可(angular代码中的url常量就不需要添加主机地址localhost:8080了,直接使用api/user/即可):

    {
        "/api/*": {  // 要访问的api的url
            "target": "http://localhost:8080", // 要访问的后台服务的主机地址
            "secure": false,
            "loglevel": "debug",
            "changeOrigin": true
       }
    }
    

    直接运行ng serve --proxy-config proxy.conf.json

    或者在package.json中配置新的script然后使用npm run 自定义的命令名即可

    举例:

    "scripts": {
      "start:proxy":"ng serve --proxy-config proxy.conf.json`"
    }
    

    运行npm run start:proxy即可自动运行ng serve指令。

    相关文章

      网友评论

        本文标题:服务器跨域问题解决办法

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