Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

json - How to access remote data and write it into a file during Nuxt build?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...