angular4 跨域访问

前端之家收集整理的这篇文章主要介绍了angular4 跨域访问前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.配置:在angular项目根目录下创建:proxy.config.json
proxy.config.json文件

{
  "/":{
    "target":"http://127.0.0.1:8080"
  }
}

"/":代表后台项目路径
"target":"http://127.0.0.1:8080"  指明访问地址

2.修改package.json 为

"scripts": {
    "ng": "ng","start": "ng serve  --proxy-config proxy.config.json","build": "ng build","test": "ng test","lint": "ng lint","e2e": "ng e2e"
  }

-----------------------------------------分割线----------------------------------------------
用 ng serve --proxy-config proxy.config.json 启动angualr项目

3.后端springboot接口:

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private UserService userService;

    @GetMapping("/getUsers")
    public String getUsers(){
        return "\"{\"aa\":\"11\"}\"";
    }
}

4.angular访问:

import { HttpClient } from '@angular/common/http';
// 用HttpClient
this.http.get('/test/getUsers').subscribe(data => {
  console.log(data);
});

自己测试通过;

猜你在找的Angularjs相关文章