[英]How to access remote data and write it into a file during Nuxt build?
我是 Nuxt JS 的新手。 我試圖弄清楚如何從遠程 URL 源下載 JSON 文件,以便在本地使用作為 nuxt 構建過程的一部分?
因此,例如,如果 JSON 文件位於:
https://path/to/my/json
然后在我的 nuxt 應用程序中,我不想遠程連接到該 JSON 文件,而是在本地使用它。 因此,當我發布我的網站時,我不希望它依賴於外部資源。
目前,我正在使用 gulp gulp-download-files
插件通過 gulp 完成此操作。
您可以從安裝axios
開始(您仍然可以在項目旁邊使用@nuxtjs/axios ):
yarn add -D axios
然后,我們拿JSON占位符的API進行測試,我們將嘗試獲取位於此處的內容: https://json1placeholder.typicode。
並將其保存到我們 Nuxt 項目中的本地.json
文件中。
為此,前往nuxt.config.js
並在那里編寫您的腳本
import fs from 'fs'
import axios from 'axios'
axios('https://jsonplaceholder.typicode.com/todos/1').then((response) => {
fs.writeFile('todos_1.json', JSON.stringify(response.data, null, 2), 'utf-8', (err) => {
if (err) return console.log('An error happened', err)
console.log('File fetched from {JSON} Placeholder and written locally!')
})
})
export default {
target: 'static',
ssr: false,
// your usual nuxt.config.js file...
}
這將為您提供一個不錯的 JSON 文件,然后您可以將其導入回您的nuxt.config.js
並繼續工作!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.