Angular添加调试跨域代理

        对于一些安全性要求较高的应用,服务端不会开启跨域访问,此时就需要前端页面进行跨域设置。

        常用的一种的方式是使用nginx进行代理:

server{
    listen 80;
    root /var/www/myappweb;
    location / {
        index  index.html index.htm;
    }
    location /api {
        proxy_pass http://192.168.1.20:8080;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

        项目部署时按照以上配置就可以满足跨域访问,Angular允许我们在调试时添加跨域代理,而不用通过nginx进行配置。

        按照以下步骤可以添加调试跨域代理:

1、添加代理配置文件

        在项目根目录下添加文件 proxy.conf.json, 在文件中写入需要代理的路径:

{
    "/api": {
        "target": "http://192.168.1.20:8080/",
        "secure": false
    }
}

        target 字段就是代理的服务端地址, secure: false 表示不检查安全问题。设置后,可以接受运行在HTTPS上,可以使用无效证书的后端服务器。

2、修改Angular调试设置

        修改项目根目录下的 angular.json 文件:

{
    ...,
    "projects":{
        "myapp":{
           ...,
           "architect":{
               ...,
                "serve":{
                    ...,
                    "options":{
                        ...,
                        "proxyConfig": "proxy.conf.json"                                            
                    },
                    ...                                    
                },
                ...                          
           },
           ...         
        }            
    },
    ...
}

        ts 代码中采用相对路径请求服务端数据:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class ApiService {
    constructor(private http: HttpClient) { }
    userSignIn(userName:string,password:string,code:string){
        let data = {userName:userName, password:password, code:code};
        return this.http.post<any>("/api/user/signin", data);    
    }
}

        完成以上设置开启调试就可以跨域请求服务端数据了。

        以上设置只适用于调试环境,部署环境还是需要外部工具(Nginx等)辅助才可以实现跨域代理访问,包括(Vue、React应用亦是如此)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_老杨_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值