express api 同時處理form與raw
寫api接收post資料可能會是raw data或form或x-www-form-urlencoded
透過header Content-Type 判斷
如果是raw conten-type會是text/plain
其他分別就會是
1. raw data
content-type==='text/plain'
raw data 無法由req.body拿到資料
必須透過
req.on('data',()=>{})接收
req.on('end',()=>{})完成接收取得完整資料
取到的完整資料會是string
2.application/x-www-form-urlencoded
content-type==='application/x-www-form-urlencoded'
直接由req.body取得資料
req.body為object物件內容
3.multipart/form-data
用來上傳檔案與資料用的
一樣可以透過req.body取到資料
但必須要有安裝multer
app.use(multer({ dest: './uploads/' }))
注意要判斷是否使用form-data
要用contentType.indexOf('multipart/form-data') !== -1 判斷
因為內容值不只multipart/form-data
 const contentType = req.get('Content-Type')  
  // 處理raw data  
  let data = ''  
 if (contentType === 'text/plain') {  
  req.setEncoding('utf8')  
  req.on('data', (chunk) => {  
   data += chunk  
  })  
  req.on('end', async() => {  
   res.send(data)  
  })  
 } else {  
  let data = req.body  
  if (typeof data === 'object') data = JSON.stringify(data)  
  res.json({ data })  
 }  
沒有留言:
張貼留言