0

mutipart/form-data URLRequest을 사용하여 이미지와 텍스트를 내 firebase 서버로 보내는 ios 앱을 만들고 있습니다.Busboy를 사용하여 Node.js의 JSON에 Mutipart/form-data

const Busboy = require('busboy'); 

exports.test = functions.https.onRequest((req, res) => { 
    console.log("start"); 
    console.log(req.rawBody.toString()); 
    if (req.method === 'POST') { 
     var busboy = new Busboy({ headers: req.headers}); 
     busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => { 
      console.log('field'); 
     }); 

     busboy.on('finish', function() { 
      console.log('finish'); 
      res.json({ 
       data: null, 
       error: null 
      }); 
     }); 

     req.pipe(busboy); 
    } else { 
     console.log('else...'); 
    } 
}); 

그러나, 위의 코드가 작동하지 않는 것 : 내 클라우드 기능의 데이터를 처리하기 위해, 내가 여기 JSON formatmutipart/form-data을 구문 분석 documentation에 언급 된 방법을 사용하고 있어요 나의 코드입니다 당신이 볼 수 있듯이, on('field') 기능이 실행되지 않을

Function execution started 
start 
--Boundary-43F22E06-B123-4575-A7A3-6C144C213D09 
Content-Disposition: form-data; name="json" 

{"name":"Alex","age":"24","friends":["John","Tom","Sam"]} 
--Boundary-43F22E06-B123-4575-A7A3-6C144C213D09-- 
finish 
Function execution took 517 ms, finished with status code: 200 

: 여기 콘솔에서 출력됩니다. 내가 놓친 게 무엇입니까?

var request = URLRequest(url: myCloudFunctionURL) 
request.httpMethod = "POST" 
request.setValue("multipart/form-data; boundary=myBoundary", forHTTPHeaderField: "Content-Type") 
request.addValue(userToken, forHTTPHeaderField: "Authorization") 
request.httpBody = myHttpBody 
let session = URLSession.shared 
session.dataTask(with: request) { (data, response, requestError) in 
    // callback 
}.resume() 
+0

'POST'절차를 포함 할 수 있습니까? – Stamos

+0

사후 절차가 포함되어 있습니다. – AlexBains

+0

1. 양식 데이터로 게시물을 작성하고 클라우드 기능이 작동하는지 확인하려면 POSTMAN과 같은 것을 시도하십시오. 2. 'myHttpBody' 생성 부분을 제외하고 코드가 훌륭하게 보입니다. 메시지를 올바르게 작성하지 않으면 올바르게 작동하지 않습니다. – Stamos

답변

0

당신은 문서의 예에 설명 된대로 busboy.end(req.rawBody); 대신 req.pipe(busboy)를 호출해야합니다 :

또한, 여기 httpRequest를 보내는 swift의 코드입니다. 나는 왜 .pipe doesnt가 ​​작동하는지 모른다. .end을 호출하면 같은 결과가되지만 다른 방식으로 생성됩니다.

const Busboy = require('busboy'); 

exports.helloWorld = functions.https.onRequest((req, res) => { 

     const busboy = new Busboy({ headers: req.headers }); 
     let formData = {}; 

     busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => { 
      // We're just going to capture the form data in a JSON document. 
      formData[fieldname] = val; 
      console.log('Field [' + fieldname + ']: value: ' + val) 
     }); 

     busboy.on('finish',() => { 
      res.send(formData); 
     }); 

     // The raw bytes of the upload will be in req.rawBody. 
     busboy.end(req.rawBody); 

});