在Angular 9中解决跨域资源共享问题的一种常见方法是使用代理配置。以下是一个示例:
proxy.conf.json
的文件,并添加以下内容:{
"/api": {
"target": "http://example.com", // 将此处替换为你的API服务器地址
"secure": false
}
}
angular.json
文件中的architect > serve > options
部分添加一个proxyConfig
属性,将其值设置为proxy.conf.json
,示例如下:"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-app:build",
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
...
}
}
}
package.json
文件中的scripts
部分,将ng serve
命令修改为ng serve --proxy-config proxy.conf.json
,示例如下:"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
...
}
ng serve
命令启动你的应用程序。现在,当你的应用程序发出以/api
开头的请求时,它将被代理到http://example.com
,并且跨域资源共享问题将被解决。例如,如果你的应用程序发出请求/api/users
,它将被代理到http://example.com/api/users
。
请记住,这只是解决跨域资源共享问题的一种方法。根据你的具体情况,可能还有其他解决方案可供选择。