다음은 해결책입니다.
첫 번째 가져 오기 모듈.
var fs = require('fs');
var request = require('request');
var crypto = require('crypto');
우리는 다중 콘텐츠 형식 및 원시 POST 요청 본문을 구축하는 다른에 대한 경계를 생성하는 두 가지 유틸리티 함수가 필요합니다.
var CRLF = "\r\n";
var md5 = crypto.createHash('md5');
function multipartRequestBodyBuilder(fields, boundary) {
var requestBody = '';
for(var name in fields) {
var field = fields[name];
var data = field.data;
var fileName = field.fileName ? '; filename="' + field.fileName + '"' : '';
var type = field.type ? 'Content-Type:' + field.type + CRLF : '';
requestBody += "--" + boundary + CRLF +
"Content-Disposition: form-data; name=\"" + name + "\"" + fileName + CRLF +
type + CRLF +
data + CRLF;
}
requestBody += '--' + boundary + '--' + CRLF
return requestBody;
}
function getBoundary() {
md5.update(new Date() + getRandomArbitrary(1, 65536));
return md5.digest('hex');
}
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
그런 다음 데이터를 구성하고 경계를 생성합니다.
var notificationValue = {
"applicationId":"2",
"schemaId":"12",
"topicId":"1",
"type":"USER"
};
var postData = {
notification : {
data : JSON.stringify(notificationValue),
type : "application/json"
},
file : {
data : fs.readFileSync("message.json"),
fileName : 'notification.json',
type : 'application/octet-stream'
}
}
var boundary = getBoundary();
그런 다음 요청을 작성하고 Kaa 서버로 전송하십시오. send notification :
var opts = {
url: 'http://localhost:8080/kaaAdmin/rest/api/sendNotification',
method: 'POST',
auth: { user: 'devuser', password: 'devuser123' },
headers: {
'content-type': 'multipart/form-data; boundary=' + boundary
},
body : multipartRequestBodyBuilder(postData, boundary)
};
request(opts, function(err, resp, body) {
if(err) {
console.log("Error: " + err);
} else {
console.log("Satus code: " + resp.statusCode + "\n");
console.log("Result: " + body);
}
});
모든 후, 당신은 상태 코드 내가 KAA 샌드 박스에서 알림 데모 테스트 전체 코드 파일을 첨부 (200)
Status code: 200
Result: {
"id" : "57e42623c3fabb0799bb3279",
"applicationId" : "2",
"schemaId" : "12",
"topicId" : "1",
"nfVersion" : 2,
"lastTimeModify" : 1474569763797,
"type" : "USER",
"body" : "CkhlbGxvAA==",
"expiredAt" : 1475174563793,
"secNum" : 17
}
와 확인 응답을 볼 수 있습니다.
당신은 최고입니다. 정말 고맙습니다. –