要在Angular CLI中使用代理将请求发送到PHP脚本,并从脚本返回代码,可以按照以下步骤进行设置:
proxy.conf.json
的文件,并添加以下内容:{
"/api/*": {
"target": "http://localhost:8000",
"secure": false,
"pathRewrite": {
"^/api": ""
},
"changeOrigin": true
}
}
这将将所有以/api
开头的请求代理到http://localhost:8000
,可以根据需要修改代理目标URL。
package.json
文件中的scripts
部分添加一个新的脚本:"scripts": {
"start": "ng serve --proxy-config proxy.conf.json"
}
这将启动开发服务器并使用刚刚创建的代理配置。
HttpClient
模块发送请求到代理URL。例如,假设有一个从PHP脚本返回代码的GET请求,可以在组件中使用以下代码:import { HttpClient } from '@angular/common/http';
export class AppComponent {
constructor(private http: HttpClient) {}
getCodeFromPhpScript() {
this.http.get('/api/script.php').subscribe((data: any) => {
console.log(data);
});
}
}
这将发送一个GET请求到http://localhost:8000/script.php
,并在控制台打印返回的代码。
npm start
命令启动开发服务器,并确保PHP脚本在代理目标URL(如http://localhost:8000/script.php
)上运行。现在,Angular应用程序将通过代理发送请求到PHP脚本,并从脚本返回代码。
上一篇:Angular CLI代理+ Django后端在Docker中无法工作
下一篇:Angular CLI到Laravel的数据传输错误('Access-Control-Allow-Origin'头)