本文介绍了如何在 Nuxt 构建期间访问远程数据并将其写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

https://path/to/my/json

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

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

解决方案

您可以从安装 axios 开始(您仍然可以拥有

I'm new to Nuxt JS. And am trying to figure out how to download a JSON file from a remote URL source to use locally as part of the nuxt build process?

So, for example, if the JSON file is at:

https://path/to/my/json

Then in my nuxt app, I DON'T want to connect to that JSON file remotely, but rather use it locally. So, when I publish my site, I don't want it to be dependent on the external resource.

At the moment, I'm accomplishing this with gulp, using the gulp-download-files plugin.

解决方案

You can start by installing axios (you can still have @nuxtjs/axios alongside your project):
yarn add -D axios

Then, let's take JSON placeholder's API for testing purposes, we will try to get the content located here: https://jsonplaceholder.typicode.com/todos/1
And save it to a local .json file in our Nuxt project.

For that, head towards nuxt.config.js and write your script there

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...
}

This will give you a nice JSON file that you can afterwards import back into your nuxt.config.js and work on!

这篇关于如何在 Nuxt 构建期间访问远程数据并将其写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 17:37