使用JQuery Ajax解析REST API 401未经授权

时间:2015-06-09 21:06:12

标签: jquery ajax api rest parse-platform

我一直在与parse.com的REST API争夺一小时但没有成功。我不断收到HTTP 401并回复{"error": "unauthorized"}

这是我的云代码:

Parse.Cloud.define("sendEmail", function(request, response) {

  var Mailgun = require('mailgun');
  Mailgun.initialize('mg.crawford.works', 'key-c67f7a53cf12b2aabeaade0e50d57e8f');

  Mailgun.sendEmail
  ({
    "to": "sales@crawford.works",
    "from": "website@crawford.works",
    "subject": "Website Form Submission",
    "text": "Name: " + request.params.name + "\nEmail:  "+request.params.email+"\nPhone: "+request.params.phone+"\nMessage: "+request.params.msg
  }, 
  {
    success: function(httpResponse) 
    {
      console.log(httpResponse);
      response.success("success");
    },
    error: function(httpResponse) 
    {
      console.error(httpResponse);
      response.error("error");
    }
  });
});

这是我的客户端代码(仅用于表单提交):

var data = {};

data.name = $("#name").val();

data.email = $("#email").val();

data.msg = $("#message").val();

data.phone = $("#phone").val();
$.ajax({
  method: 'post',
  url: "http://api.parse.com/1/functions/sendEmail",
  data: JSON.stringify(data),
  contentType: 'application/json',
  headers: 
  { 
    'X-Parse-Application-Id': 'This is the right key, triple checked',
    'X-Parse-REST-API-Key': 'Same story here'
  }
})
.done(function (response) {
  if (response.success == 'success') {               
    alert('success');                       
  } else {
    alert('fail');
  }
});
return false; // required to block normal submit since you used ajax

我已经看过许多像这样的解析支持了四分之一(StackOverFlow不允许我把更多的链接放在b / c我仍然是noob):https://www.parse.com/questions/401-unauthorized-error-with-parse-rest-api

感谢您提供的任何帮助,

@acrawly

2 个答案:

答案 0 :(得分:0)

所以这段代码最终起作用了,我无法弄清楚原因:

$.ajax("https://api.parse.com/1/functions/sendEmail", {
                dataType: 'json',
                method:'post',
                contentType: "application/json",
                data: JSON.stringify(data),
                headers: { 'X-Parse-Application-Id': 'sameKey',
                      'X-Parse-REST-API-Key': 'sameKeyAgain'
                },
                success: function(data) { //<-- I thought maybe success vs done was it but 
                     //I changed this out and no diff in the result

                    if(data.result === 'success')
                    {
                        alert("success");
                    }
                    else
                    {
                        alert("error");
                    }

                },
                error: function(data) {
                    alert(data);
                }
            });
编辑:正如@hasen在下面指出的那样,那是因为我没有使用HTTPS。

答案 1 :(得分:0)

调用云功能时,您应该在URL中https而不是http,但要获取文件,请使用http