【问题标题】:Converting cURL to angular将 cURL 转换为角度
【发布时间】:2018-03-30 21:24:13
【问题描述】:

我有一个很好用的 cURL 命令:

curl https://{{mydomain}}.zendesk.com/api/v2/tickets.json \
  -d '{"ticket": {"subject": "Testing!", "type":"problem", "priority":"low", "custom_fields": [{"id": 25227383, "value": "support"}, {"id": 24746086, "value": "customer"}, {"id": 24621686, "value": "product"}, {"id": 24462503, "value": "yes"}], "comment": { "body": "Description" }}}' \
  -H "Content-Type: application/json" -v -u {{email}}/token:{{token}} https://obscura.zendesk.com/api/v2/users.json

我尝试将其转换为角度 5:

const body = {"ticket": 
{"subject": "Testing!",
"type":"problem", 
"priority":"low", 
"custom_fields": 
[{"id": 25227383, "value": "support"},
{"id": 24746086, "value": "customer"}, 
{"id": 24621686, "value": "product"}, 
{"id": 24462503, "value": "yes"}], 
"comment": { "body": "Description" }}};

this.http.post('https://{{mydomain}}.zendesk.com/api/v2/tickets.json', 
{data: body,
headers:{'Content-Type': 'application/json',
'Authorization': 'Bearer {{email}}/token:{{token}}',
'Access-Control-Allow-Origin': '*'}})
.toPromise().then(function(response) {
console.log(response.toString());
})

我收到如下错误:

POST https://{{mydomain}}.zendesk.com/api/v2/tickets.json 401 (Unauthorized)

Failed to load https://{{mydomain}}.zendesk.com/api/v2/tickets.json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.

ERROR Error: Uncaught (in promise): Response with status: 0 for URL: null
at resolvePromise (zone.js:824)
at resolvePromise (zone.js:795)
at eval (zone.js:873)
at ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (core.js:4620)
at ZoneDelegate.invokeTask (zone.js:424)
at Zone.runTask (zone.js:192)
at drainMicroTaskQueue (zone.js:602)
at ZoneTask.invokeTask [as invoke] (zone.js:503)
at invokeTask (zone.js:1540)

我认为我的身份验证有问题。

有人有什么建议吗?

谢谢

【问题讨论】:

    标签: angular authentication curl zendesk


    【解决方案1】:

    您可能需要确保按照 ZenDesk 的文档使用 OAuth 身份验证: https://help.zendesk.com/hc/en-us/articles/115005580188-Making-cross-origin-browser-side-API-requests

    它们不允许使用基本身份验证或 API 令牌的跨源请求。

    【讨论】:

    • 正确,应该通过服务器发出请求,以保护在客户端暴露的令牌。
    【解决方案2】:

    当您直接使用 CURL、Postman 或类似的东西发出 Http 请求时,您不需要设置 CORS 标头。但是现在您正在从您的网络应用程序(Angular)发出 Ajax 调用,您正在从另一个域 clocalhost 发出请求)所以您应该设置标题: 访问控制允许来源 在您的要求中。通常你也需要在服务器端进行这样的配置,这通常是通过配置文件完成的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-15
      • 2023-03-27
      • 1970-01-01
      • 2023-01-20
      • 2017-06-05
      • 2020-08-23
      • 2016-01-08
      • 2018-03-28
      相关资源
      最近更新 更多