对于一些安全性要求较高的应用,服务端不会开启跨域访问,此时就需要前端页面进行跨域设置。
常用的一种的方式是使用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应用亦是如此)。

1744

被折叠的 条评论
为什么被折叠?



