json - 如何在 Nuxt 构建期间访问远程数据并将其写入文件?
问题描述
我是 Nuxt JS 的新手。我试图弄清楚如何从远程 URL 源下载 JSON 文件以在本地使用作为 nuxt 构建过程的一部分?
因此,例如,如果 JSON 文件位于:
https://path/to/my/json
然后在我的 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...
}
这将为您提供一个不错的 JSON 文件,然后您可以将其导入回您的文件中nuxt.config.js
并继续工作!
推荐阅读
- vue.js - 在 vue.js/nuxt.js 中从 Wordpress API (Elementor) 转换 html
- powershell - 如何在powershell中过滤输出的一部分
- unit-testing - 模拟伴随对象方法 mockito 的返回值
- ip - 如何访问 Tornado 远程服务器?
- php - 用户注册 - 显示用户上传图片
- typescript - 类型扩展不适用于通用累加器
- sql - 如何在SQL中合并两个表并将具有相同ID的值相加?
- firebase - 如何从 Firebase Firestore 访问特定用户的信息?
- firebase - 如何在 GCP 中启用 Firebase 实时数据库?
- .htaccess - 我可以在 .htaccess 文件中有条件行吗?