2017-12-14 12 views
-1

投稿データをAPIに送信するにはどうすればよいですか。私は角度からノードまでのファイルを収集しましたが、console.log()で表示できますが、角度から取得したデータファイルがポストリクエストを使用してノードjsを使用してapiに送信する方法がわかりません。角度からノードへファイルを送信し、ポストリクエストを使用してAPIにリクエストしますか?

私のノードにこのコードがあり、ノードjsのリクエストモジュールを使用しています。

'use strict'; 

import _ from 'lodash'; 
import request from 'request'; 

function fetch(method, url, req) { 
    return new Promise(function(resolve, reject) { 
    var options = { 
     method: method, 
     url: url, 
     headers: { 
     'Content-Type': 'application/json' 
     } 
    } 
    if (method === 'GET' || method === 'DELETE') { 
     options.headers = {}; 
     options.qs = req.query; 
    } else { 
     if (method !== 'DELETE') { 
     options.body = JSON.stringify(req.body); 
     } 
    } 
    if (req.headers.authorization) { 
     options.headers['Authorization'] = req.headers.authorization; 
    } 
    if (method === 'DELETE') { 
     delete options.qs; 
    } 
    console.log(req.file); 
    request(options, function(error, response, body) { 
     if (error) { 
     return reject(error); 
     } 
     if (response.statusCode === 500) { 
     return reject(body); 
     } 
     if (response.statusCode === 204) { 
     return resolve({status: response.statusCode, body: 'no-content'}); 
     } 
     try { 
     var parsed = (typeof(body) === 'object') ? body : JSON.parse(body); 
     return resolve({status: response.statusCode, body: parsed}); 
     } catch(e) { 
     return reject('[Error parsing api response]: ' + e); 
     } 
    }); 
    }); 
} 

module.exports = { 
    get: function(url, req) { 
    return fetch('GET', url, req); 
    }, 
    post: function(url, req) { 
    return fetch('POST', url, req); 
    }, 
    put: function(url, req) { 
    return fetch('PUT', url, req); 
    }, 
    delete: function(url, req) { 
    return fetch('DELETE', url, req); 
    } 
}; 

答えて

-1
// When selecting a file on the front-end you should be able to find the file in: event.target.files[0] for the event you are triggering when selecting a file. 

// You can then send from your front-end to your back-end by using a multipart form data submission: 



var formData = new FormData(); 

formData.append('name', event.target.files[0].name); 
formData.append('file', event.target.files[0]); 

var config = { 
    headers: { 'content-type': 'multipart/form-data' } 
}; 

const url = '/api/your-proper-endpoint/'; 
// I'm using axios for http requests but you can use whatever 
// you'd like 
axios.post(url, formData, config) 

// If you're then using something like expressJS on your back-end you can use an npm package like multer to receive your file in your API route. 

// https://www.npmjs.com/package/multer 


// example route function in ExpressJS which reads saves a file sent from 
// the client, saves it temporarily to an empty server side folder I have 
// called uploads, then reads the saved file. From there you could send it 
// again to another API if needed, or you could just send the file to the 
// final API in the first place from the client 

    const multer = require('multer'); 
    const xlsx = require('node-xlsx'); 
    const fs = require('fs'); 

    module.exports = (req, res) => { 
     return new Promise((resolve, reject) => { 
      // set current moment for unique file names 
      const dt = Date.now(); 

      // store file using multer so that the it can be parsed later by node-xlsx(or another module method like fs.readFileSync) 
      const storage = multer.diskStorage({ 
       destination: (req, file, cb) => { 
        cb(null, `${__dirname}/uploads`) 
       }, 
       filename: (req, file, cb) => { 
        cb(null, `${file.fieldname}-${dt}.xlsx`) 
       } 
      }); 

      const upload = multer({ //multer settings 
       storage: storage, 
       fileFilter: (req, file, callback) => { //file filter if you want to validate file extensions 
        if (['xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length - 1]) === -1) { 
         return callback(new Error('Wrong file type')); 
        } 

        callback(null, true); 
       } 
      }).single('file'); 

      // read multi-part form upload using multer 
      upload(req, res, (err) => { 
       if (err) { 
        reject({ err: err }); 
       } else { 
        try { 
         // parse JSON from excel file stored by multer 
         const workSheetsFromBuffer = xlsx.parse(fs.readFileSync(`${__dirname}/uploads/${req.file.fieldname}-${dt}.xlsx`)); 

         // delete file once finished converting excel to JSON 
         fs.unlink(`${__dirname}/uploads/${req.file.fieldname}-${dt}.xlsx`, (deleteFileErr) => { 
          if (deleteFileErr) { 
           reject({ err: deleteFileErr }); 
          } else { 
           resolve(workSheetsFromBuffer); 
          } 
         }); 
        } catch (bufferError) { 
         reject({ err: bufferError }); 
        } 
       } 
      }); 
     }); 
    }; 
+0

答えをいただき、ありがとうございます。私はすでに解決策を見つけました。 – user8956707

関連する問題