【问题标题】:Curl to $http.post() for Angular JS为 Angular JS 卷曲到 $http.post()
【发布时间】:2017-03-10 14:20:12
【问题描述】:

有人能告诉我如何将下面列出的 curl 代码转换为 Angular js 的 $http.post() 吗?任何帮助将非常感激。谢谢!

curl https://example.zendesk.com/api/v2/organizations.json \
 -H "Content-Type: application/json" \
 -d '{"organization": {"name": "My Organization"}}' \
 -v -u {email_address}/token:{api_token}

到目前为止,我已经设置了以下 angularjs 代码:

                     $http({
                            method : "POST",
                            url : url,
                            data : angular.toJson($scope.form),
                            headers : {
                                'Content-Type' : 'application/json'
                            }
                        }).then(Success,Failure);

我只是不知道如何在通话中设置电子邮件地址和令牌。

【问题讨论】:

  • 到目前为止,您尝试过什么尝试转换为 $http.post()
  • 我已经用我迄今为止尝试过的内容更新了我的问题。
  • 你不能也不应该。您真的不想公开您的 api 令牌/密钥。您应该创建一个将转发该信息的后端服务。
  • 我设置了一个后端服务,可以在需要时调用 api 令牌,这样不会有太大问题。我现在需要的是转换这个卷曲......

标签: javascript html angularjs curl post


【解决方案1】:

我认为我能给你的最好建议是不要在前端发出 CORS 请求。您希望分离关注点,您的后端最好调用 api 令牌,然后将该数据解析为 JSON。最后,您有一个后端端点/路由,前端可以在其中发送数据请求。

在您的后端,您设置的路线将如下所示:

router.post('/api/data', (req, res) => {
    request('https://example.zendesk.com/api/v2/organizations.json', {
        headers: { ... }, token: { ... }
    }).then((result) { res.json(result) };
});

在您的 Angular 工厂/服务中,您将发出如下 HTTP 请求:

$http.post('localhost/api/data')
    .then((response) => { response = response.data })
    .catch((error) => { if (err) { console.log(err) })

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2016-12-06
    • 2016-12-28
    • 2016-01-18
    • 2014-05-29
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多