【问题标题】:CORS error when using Back4App Parse Cloud Code Function使用 Back4App 解析云代码功能时出现 CORS 错误
【发布时间】:2018-12-02 20:12:51
【问题描述】:

我有一个在 Back4App 上运行的 Parse 后端。它们具有云代码功能,可让您将 NodeJ 之类的函数放在您可以从站点上的 javascript 调用的函数中。我对 NodeJ 不太熟悉,所以我的函数语法可能有问题。

NodeJs 函数需要调用 mailgun REST API,我从我网站上的 Coffee Script 调用 Parse 云代码函数。我通过获取对在 Postman 上工作的 mailgun 的 REST 调用然后使用 Postman 的代码生成来生成 NodeJs 函数来创建我的函数。

问题是当我从我的网站调用 Parse 云代码函数时,我收到以下错误:

[Error] Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin.
[Error] Failed to load resource: Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin. (sendemail, line 0)

无论是来自本地测试站点还是托管测试站点,我都会收到此错误。

这是Back4App解析服务器上的云代码函数:

    Parse.Cloud.define("sendemail", function(request, response) {
    var request = require("request");

    var options = { method: 'POST',
      url: 'https://api.mailgun.net/v3/mg.mysite.com/messages',
      headers: 
      { 'Access-Control-Allow-Origin':'*',
        'Access-Control-Allow-Headers':'X-Requested-With',
        'Access-Control-Allow-Headers':'Content-Type',
        'Postman-Token': 'token',
        'cache-control': 'no-cache',
        Authorization: 'Basic <auth_token>',
        'Content-Type': 'application/x-www-form-urlencoded',
        'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
      formData: 
      { from: 'MySite.com <quote@mysite.com>',
        to: 'myemail@gmail.com',
        subject: 'Email Test',
        text: 'Email Test' } };

    request(options, function (error, response, body) {
      if (error) throw new Error(error);

      console.log(body);
    });
});

我使用以下咖啡脚本从我的网站调用此解析云代码函数:

   Parse.Cloud.run('sendemail', data, {
    success: () ->
      console.log(result)
      console.log("success")
    ,
    error: () ->
      console.log(error)
      console.log("fail")
  });

似乎我缺少 Back4App 上的一个设置。我搜索了 Parse 的所有设置,但没有看到指定 Access-Control-Allow-Origin 的地方。我搜索了 Back4App 和社区组的 API 文档。社区组提到了问题here,但除了联系community@back4app.com 之外并没有真正给出答案。我已经这样做了,但我需要尽快得到答复。

Back4App 上还有一个名为 hello 的测试函数,我可以正常调用它并得到 200 响应。

Parse.Cloud.define("hello", function(request, response) {
  response.success("Hello world!");
});

【问题讨论】:

标签: cors coffeescript parse-cloud-code back4app


【解决方案1】:

我认为您忘记了 { 和 } 来定义函数。您还必须使用 => 代替 ->。

尝试使用 promise 中的“then”和“catch”。这里有两个可以用来测试的 sn-ps:

  Parse.Cloud.run('sendemail', data).then(() => {
      console.log(result)
      console.log("success")
    }).catch((error) => {
      console.log(error)
      console.log("fail")
    });

或另一个:

  Parse.Cloud.run('sendemail', data, {
    success: () => {
      console.log(result)
      console.log("success")
    },
    error: (error) => {
      console.log(error)
      console.log("fail")
    }
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 2017-07-08
    • 2022-01-08
    • 2018-08-03
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多