2016-09-21 4 views
1

kaa 서버에 알림을 보내려고합니다. 아래의 cURL 명령은 정상적으로 작동하지만 node.js 서버에서 POST 요청을 보내려고합니다. 친절하게도 게시 요청으로 변환하는 데 도움이됩니다. kaa 서버로 알림 보내기 요청을 게시하려면 cURL 명령을 변환하십시오.

curl -v -S -u devuser:devuser123 -F'notification= 
{"applicationId":"32769","schemaId":"32778","topicId":"32770","type":"USER"}; 
type=application/json' -F [email protected] "http://localhost:8080/kaaAdmin/rest/api/sendNotification" | python -mjson.tool 

나는 다음과 같은 시도 :

var notificationValue= {"applicationId":"32769","schemaId":"32778","topicId":"32770","type":"USER"}; 
var file = 'notification.json'; 
var opts = { 
    url: 'http://localhost:8080/kaaAdmin/rest/api/sendNotification', 
    method: 'POST', 
    auth: { user: 'devuser', password: 'devuser123' }, 
    json: true, 
    formData: { 
      notification: JSON.stringify(notificationValue), 
      file : fs.readFileSync(file) 
    } 

}; 
request(opts, function(err, resp, body) { 
    if(err) 
     res.send(err); 
    else{ 
     res.send(body); 
    } 
}); 

나는 점점 오전 : 오류 400 필수 요청 부분 '알림'존재하지 않습니다.

답변

3

다음은 해결책입니다.

첫 번째 가져 오기 모듈.

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 
} 

와 확인 응답을 볼 수 있습니다.

+0

당신은 최고입니다. 정말 고맙습니다. –