angular - 将 Curl 请求转换为 Angular 请求
问题描述
我对这个 CURL 请求有疑问。如果我通过终端发送它可以正常工作,但是当我将它转换为 Angular HTTP 客户端调用时它不起作用。
卷曲:
curl --location --request PUT '<some_url>' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data-raw '{
"status": "CONFIRMED"
}'
角度:
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Accept', 'application/json; charset=UTF-8');
const b = {
status: 'CONFIRMED'
};
return this.http.put(some_url, b, { headers });
错误:从源“http://localhost:4200”访问 <some_url> 已被 CORS 策略阻止:在预检响应中 Access-Control-Allow-Methods 不允许方法 PUT。
解决方案
试试这个代码:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept', 'application/json; charset=UTF-8'
}),
};
const b = {
status: 'CONFIRMED'
};
return this.http<any>(some_url, b,httpOptions)
.pipe(catchError(this.errorHandler));
使用 proxy.config.json 文件
{
"/api/*": {
"target": "http://backendurl",
"secure": false,
"changeOrigin": true
}
}
在 serve->options 下添加代理配置 angular.json :
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
"proxyConfig": "src/proxy.conf.json" // add this ligne
},
推荐阅读
- angular6 - 我无法从已存储服务数组的数组中找到元素。在控制台输出中它总是显示未定义的消息
- javascript - 当我按 Enter 时
- python - 如何计算二进制消息之间的距离?
- sharepoint - SharePoint 中的可配置静态选项卡
- simulation - 到达特定补丁后如何让乌龟执行特定任务?
- loops - Ansible with_items loop over groups, defined as a list
- python - How can I insert image to Google spreadsheets using Python?
- javascript - Javascript减去双数
- php - 如果使用优惠券,则删除一个支付网关
- pdf - 如何将 OCR 文本从一个 PDF 传输到另一个 PDF?