首页 > 解决方案 > 如何在 Nuxt 构建期间访问远程数据并将其写入文件?

问题描述

我是 Nuxt JS 的新手。我试图弄清楚如何从远程 URL 源下载 JSON 文件以在本地使用作为 nuxt 构建过程的一部分?

因此,例如,如果 JSON 文件位于:

https://path/to/my/json

然后在我的 nuxt 应用程序中,我不想远程连接到该 JSON 文件,而是在本地使用它。因此,当我发布我的网站时,我不希望它依赖于外部资源。

目前,我正在使用gulp-download-files插件通过 gulp 完成此操作。

标签: jsonvue.jsnuxt.js

解决方案


您可以从安装开始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...
}

这将为您提供一个不错的 JSON 文件,然后您可以将其导入回您的文件中nuxt.config.js并继续工作!

在此处输入图像描述


推荐阅读