当本地主机的Angular后端调用受Cloudflare SSL保护的API时失败,可能是由于SSL证书验证失败导致的。为了解决这个问题,可以尝试以下方法:
import { HttpsAgent } from 'https';
import * as fs from 'fs';
const httpsAgent = new HttpsAgent({
ca: fs.readFileSync('/path/to/cloudflare_root_cert.pem'),
});
在上面的代码示例中,你需要将/path/to/cloudflare_root_cert.pem
替换为你自己的Cloudflare根证书路径。
import { HttpsAgent } from 'https';
const httpsAgent = new HttpsAgent({
rejectUnauthorized: false,
});
请注意,禁用SSL证书验证可能会引入安全风险,因此只应在开发环境中使用。
headers
选项以绕过SSL证书验证:import { HttpClient } from '@angular/common/http';
const httpOptions = {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
},
};
@Injectable()
export class ApiService {
constructor(private http: HttpClient) {}
getData(): Observable {
return this.http.get('https://api.example.com/data', httpOptions);
}
}
在上面的代码示例中,我们添加了一些CORS(跨域资源共享)头信息,以允许来自任何源的请求。
请注意,这些解决方法中的一些可能会引入安全风险,因此请在生产环境中谨慎使用。最好的解决方法是使用正确的根证书来验证SSL连接。