簡體   English   中英

使用離子推送的請求正文中的json無效

[英]Invalid json in request body using ionic push

找不到我的req對象出了什么問題。 嘗試在回調中發送推送通知時收到此錯誤。 試圖使用jslint.com鏈接我的請求數據,這沒有任何問題。 為此被抓了幾個小時!

{“ link”:null,“ message”:“請求正文中的JSON無效。對於空JSON,請傳遞'{}'。”,“ type”:“ UnprocessableEntity”}

我的代碼如下:

var title = req.body.title,
  message = req.body.message;

// Define relevant info
var ionic_api_token = 'eyJ0eXAiOTdGb-xQVQaD2sV7qTh7XNKCnwiJKV1QiLJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2MjiNC03YjE5LTQ3MzMtYjJhMy0zM2Y3MjBkYzU4MjcifQ.s3e6pCwlVUBAs8kvbO';
var device_tokens = ['d44pDarVamnNJS2cNJ2modyBxjZZxcHLlnhQN4wZkJdbgkOw96rq9EEv2WCA5MKU6do0pJoO5rsmQsBAecFt4OIFB0hhD4Dp2K-uMbjum828j-8LKtpCTtGoIDBUvYI6L'];
var ionic_security_profile = 'main';

// Build the request object
var req = {
  method: 'POST',
  url: 'https://api.ionic.io/push/notifications',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + ionic_api_token
  },
  data: {
    "tokens": device_tokens,
    "profile": ionic_security_profile,
    "notification": {
      "title": title,
      "message": message,
      "android": {
        "title": title,
        "message": message
      },
      "ios": {
        "title": title,
        "message": message
      }
    }
  }
};

function callback(error, response, body) {
  console.log(body)
}

request(req, callback);

});

唯一可能引起問題的是標題和消息對象(可能是字符串)。 請嘗試轉義,如下所示

function escapeJson(json) {
   return JSON.parse(JSON.stringify(json));
}

title = escapeJson(title);
message = escapeJson(message);

var req = {
  method: 'POST',
  url: 'https://api.ionic.io/push/notifications',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + ionic_api_token
  },
  data: {
    "tokens": device_tokens,
    "profile": ionic_security_profile,
    "notification": {
      "title": title,
      "message": message,
      "android": {
        "title": title,
        "message": message
      },
      "ios": {
        "title": title,
        "message": message
      }
    }
  }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM