【问题标题】:SyntaxError: Unexpected token < in JSON at position 1 at JSON.parse (<anonymous>)SyntaxError:JSON.parse (<anonymous>) 位置 1 处的 JSON 中的意外标记 <
【发布时间】:2018-06-04 19:04:47
【问题描述】:

我正面临这个错误,我不知道我的代码问题出在哪里 错误说 未定义:2 SyntaxError:位置 1 的 JSON 中的意外标记

我的代码,我不知道问题出在哪里,请有人帮助我

function sendTextMessage(recipientId, messageText) { 
let text = messageText.toLowerCase();
// Get Data From a Google Sheet
var google_sheet_json = "https://spreadsheets.google.com/feeds/list/" + 
process.env.GOOGLE_SHEET_ID +"/od6/public/values?alt=json";
request.get(google_sheet_json, function (err, res, body) {
 if (!err) {
  var bot_script_obj = JSON.parse(body);
  var all_bot_scripts = bot_script_obj.feed.entry;

  var i = 0;
  var len = all_bot_scripts.length;
  var all_keywords = [];
  for (; i < len; ) {

    if (text.includes(bot_script_obj.feed.entry[i].gsx$incoming.$t)){
      var messageText = bot_script_obj.feed.entry[i].gsx$outgoing.$t;
      var messageData = {
        recipient: {
          id: recipientId
        },
        message: {
          text: messageText
        }
      };
      callSendAPI(messageData);
    }
    i++;
  }
} else {
  console.log(err);
    }
    });
  }

   function callSendAPI(messageData) {
   request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: process.env.PAGE_ACCESS_TOKEN },
     method: 'POST',
     json: messageData

   }, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var recipientId = body.recipient_id;
  var messageId = body.message_id;

  console.log("Successfully sent generic message with id %s to recipient %s", 
    messageId, recipientId);
} else {
  console.error("Unable to send message.");
  console.error(response);
  console.error(error);
  }
 });  
 }

【问题讨论】:

  • 您正在使用 JSON.parse 来解析您的响应,但它似乎不是 JSON
  • 我敢打赌,您的请求失败(例如 4xx),并且后端返回给您的是 HTML 而不是 JSON。查看您收到的响应正文,它将帮助您调试。

标签: json


【解决方案1】:

似乎收到的body 参数不是 JSON,而是 HTML。

【讨论】:

  • 还可以调试此尝试console.log(this.responseText); 以获取 Ajax 响应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-05
相关资源
最近更新 更多