您当前的位置: 首页 >  ar

培根芝士

暂无认证

  • 1浏览

    0关注

    446博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Angular解决http请求跨域问题

培根芝士 发布时间:2020-11-20 15:49:33 ,浏览量:1

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

假设要把所有到 http://localhost:4200/api 的调用都转给运行在 http://localhost:8888/api 上的服务器,或者把到 http://localhost:4200/appapi 的调用转发给运行在 http://xxx.xxxx.net/ 上的服务器

则在 proxy.conf.json 中添加以下内容:

{
    "/api": {
        "target": "http://localhost:8888",
        "secure": false
    },
    "/appapi": {
        "target": "http://xxx.xxxx.net",
        "secure": false,
        "pathRewrite": {
            "^/appapi": ""
        },
        "changeOrigin": true,
        "logLevel": "debug"
    }
}

pathRewrite 能让你在运行时重写 URL 路径。 比如,你可以在代理配置中指定 pathRewrite 值为 "^/appapi": "",以移除路径末尾的 "appapi" 部分。 

changeOrigin 如果你要访问的后端不在 localhost 上,需要设置 changeOrigin 为 true。

logLevel 代理的有效日志级别是 info(默认值)、debugwarnerror 和 silent

  • 修改package.json

修改启动命令,默认使用npm start时使用代理文件配置的代理

也可以直接使用下面命令启动

ng serve --proxy-config proxy.conf.json
  • 发起网络请求

修改app.module.ts,引入HttpClientModule

使用HttpClient请求接口,请求的url不需要带域名,默认请求的是http://localhost:4200的服务,如果请求的域名已经在proxy.conf.json配置好了,则会转发到对应的域名。

创建一个 login.service.ts 来处理网络请求:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from "@angular/core";

@Injectable()
export class LoginService {
    private headers: HttpHeaders;
    constructor(private http: HttpClient) {
        this.headers = new HttpHeaders();
        this.headers.set('Content-Type', 'application/json');
    }

    public query() {
        return this.http.get('/api/query?adid=1&accesstoken=2', {
            headers: this.headers
        })
        .toPromise()
        .then((data: any) => {
          console.log("success:", data);
          return data;
        })
        .catch((err) => {
           console.log("error:", err);
        });
    }
}

在 app.module.ts 中 将LoginService添加到providers中

在login.component.ts中引入LoginService

import { LoginService } from './login.service';

export class LoginComponent implements OnInit {

  constructor(private loginService: LoginService) { }

  ngOnInit(): void {
  }
  
  onClick() {
    this.loginService.query().then((data) => {
      console.log(data);
    });
  }

}

 

关注
打赏
1660824269
查看更多评论
立即登录/注册

微信扫码登录

0.0375s