Shintaro Takechi
Shintaro Takechi

Reputation: 1365

Nuxt.js calling axios to get a local file fails with 404. However calling external URL then changing to local file works

Stripping down to the minimal vue file, following is what I have.

<template>
    <div class="container">
        <pre>{{html_data}}</pre>
    </div>
</template>

<script>
const axios = require('axios');

let url="/test.txt";

export default {
    asyncData: async function() {
        let result = await axios.get(url);
        return { html_data: result.data };
    },
}
</script>

I can see that the nuxt's local file looks at static folder, so I placed my test.txt file in static folder. And I am able to access http://localhost:3000/test.txt without 404 not found.

Opening http://localhost:3000/axios (my vue file's name is axios.vue), the screen shows NuxtServerError Request failed with status code 404. However, if I change the url to external (such as http://jsonplaceholder.typicode.com/posts) it works perfectly fine.

What is more odd is that once I open external site, and change the url and wait for the hot reload, the local file using let url="/test.txt"; displays as expected.

What exactly am I missing here?

Upvotes: 1

Views: 495

Answers (1)

Luke Carr
Luke Carr

Reputation: 36

It looks like making Axios requests to files in the static directory doesn't work when called from inside asyncData(). You have to specify the whole URL (with the base, so http://localhost:3000/test.txt in your case) or make the request in the mounted() hook.

Someone had a similar experience in this issue.

Upvotes: 2

Related Questions