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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With