要解决Angular中POST请求变成OPTIONS请求的CORS问题,可以尝试使用代理服务器来转发请求。以下是一个示例代码:
proxy.conf.json
文件来配置代理服务器,内容如下:{
"/api": {
"target": "http://backend-api-url",
"secure": false,
"changeOrigin": true,
"pathRewrite": {
"^/api": ""
}
}
}
angular.json
文件中的architect
部分添加以下内容:"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-app:build",
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
"browserTarget": "your-app:build:production"
}
}
},
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class YourService {
private apiUrl = '/api';
constructor(private http: HttpClient) { }
postData(data: any) {
return this.http.post(`${this.apiUrl}/your-endpoint`, data);
}
}
请确保将your-app
替换为你的应用程序名称,并将http://backend-api-url
替换为你的后端API的URL。
使用代理服务器转发请求时,Angular应用程序将向代理服务器发送请求,然后代理服务器将请求转发到后端API。这样可以避免浏览器发送OPTIONS请求,解决CORS问题。