【问题标题】:HttpErrorResonse Unexpected token S in JSON at position 0 FirebaseHttpErrorResonse 位置 0 Firebase 中 JSON 中的意外令牌 S
【发布时间】:2020-08-04 00:32:06
【问题描述】:

我正在使用 google firebase 云功能。

从客户端访问我的云功能时,我收到以下 HttpError

SyntaxError: Unexpected token S in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:13445:51)
    at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:13121:35)
    at Object.onInvokeTask (http://localhost:4200/vendor.js:71621:33)
    at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:13120:40)
    at Zone.runTask (http://localhost:4200/polyfills.js:12888:51)
    at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:13203:38)
    at invokeTask (http://localhost:4200/polyfills.js:14361:18)
    at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:14398:25)

text: "Sended"

下面是我的服务器代码,

exports.sendMail = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
      .....
      return transporter.sendMail(mailOptions, (erro, info) => {
        if (erro) {
          return res.send(erro.toString());
        }
        return res.send('Sended');
      });
    })
  });

});

请告诉我我在这里做错了什么?

【问题讨论】:

  • res.send 似乎期待 json 而不是字符串 'Send'

标签: javascript angular typescript google-cloud-functions httprequest


【解决方案1】:

修改代码如下:

exports.sendMail = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
    .....
        return transporter.sendMail(mailOptions, (erro, info) => {
            if (erro) {
                return res.status(500).json({"message":erro.toString()});
            }
            return res.status(200).json({"message":"Sent"})
        });
    })
});

在您的请求响应中指定 HTTP 状态代码并通过它发送标准 JSON 数据是一种很好的做法。 我自己总是为此类请求发送“消息”字段。

【讨论】:

    猜你喜欢
    • 2016-12-13
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2017-02-10
    • 2020-02-05
    • 2021-09-12
    • 2018-10-17
    相关资源
    最近更新 更多