use*_*793 4 json vue.js nuxt.js
我是 Nuxt JS 的新手。我想弄清楚如何从远程 URL 源下载 JSON 文件以在本地使用作为 nuxt 构建过程的一部分?
例如,如果 JSON 文件位于:
https://path/to/my/json
Run Code Online (Sandbox Code Playgroud)
然后在我的 nuxt 应用程序中,我不想远程连接到该 JSON 文件,而是在本地使用它。因此,当我发布我的网站时,我不希望它依赖于外部资源。
目前,我正在使用该gulp-download-files插件通过 gulp 来完成此操作。
您可以从安装开始axios(您仍然可以将@nuxtjs/axios与您的项目一起使用):
yarn add -D axios
然后,让我们使用JSON 占位符的 API进行测试,我们将尝试获取此处的内容: https: //jsonplaceholder.typicode.com/todos/1
并将其保存到我们的 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...
}
Run Code Online (Sandbox Code Playgroud)
这将为您提供一个不错的 JSON 文件,您可以稍后将其导入回您的文件中nuxt.config.js并进行处理!