2017-08-30 38 views
0

我有一個快速/節點應用程序,通過express/router/like/user等類似的路由器暴露GET終點。響應是一個JSON,我想當我打localhost:8080/api/user時將JSON下載到文件中。在express/node應用程序中保存對一個文件的HTTP GET響應

我試過res.download但不知道如何處理它的響應數據。這可能是一個重複的問題,但我無法找到一個特別針對這個用例的例子。

當在瀏覽器中調用端點時,它應該提示下載,然後應該下載到默認位置。

router.route('/user') 
.get((req, res) => { 
MyService.get().then((result) => { // the get method resolves a promise with the data 
    // Prompt for download 
}).catch((err) => { 
    console.log(err); 

    res.status(500).json({ 
    status: 500, 
    data: err 
    }); 
}); 
}); 

回答

0

所以我能做到這一點在以下2種方式之一,

router.route('/user') 
.get((req, res) => { 
MyService.get().then((result) => { 
res.attachment('users.csv'); 
/*or you can use 
    res.setHeader('Content-disposition', 'attachment; filename=users.csv'); 
    res.set('Content-Type', 'text/csv');*/ 
res.status(200).send(result); 
}).catch((err) => { 
console.log(err); 
    res.status(500).json({ 
    status: 500, 
    data: err 
    }); 
}); 
}); 
0

如果我理解正確,您想要將發送的數據/api/user保存到您在路由中發送的文件中?

var fs = require('fs') 

app.get("/api/user", function(req, res){ 

    var data = fromDb() 
    fs.writeFileSync("/tmp/test", JSON.stringify(data)) 
    res.send(data) 

}) 
+0

謝謝您的答覆。我需要的僅僅是當我點擊/ api /用戶端點 – Sai

+0

時下載對文件的響應。然後我的方法適用於你。 – Ozgur

0

如果我有你的權利,然後你可以嘗試Content-TypeContent-disposition頭象下面這樣:

res.writeHead(200, {'Content-Type': 'application/force-download','Content-disposition':attachment; filename={your_file_name}.json}); 
res.end(data); 

注意

  • res.end(data)data是你的JSON數據。

  • {your_file_name}.json是你的實際文件名,給它任何名字。

+0

謝謝你的迴應。有沒有辦法使用express.js本地執行此操作? – Sai