Adam
Adam

Reputation: 91

Returning JSON with Vue Router

I need to return a JSON object when users hit /nav on my application. This JSON is used programmatically and cannot be just a string.

Is there a way to make a vue component that is only JSON? Or a way to tell the router to return JSON?

Thank you!

Upvotes: 9

Views: 6076

Answers (2)

Pascal Ganaye
Pascal Ganaye

Reputation: 1364

I had a very similar problem. I wanted /nav to return JSON but only on my local development server however.

So I just created a vue.config.js file (in my app root folder)

module.exports = {
  devServer: {
    before: function(app, server) {
      app.get('/nav', function(req, res) {
        const result = { x:1 , y : "hello" };
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify(result));
      });
    }
  }
}

With this files when I run npm run serve, I get the json object when navigating to /nav and my regular app otherwise.

Upvotes: 2

divine
divine

Reputation: 4922

Is there a way to make a vue component that is only JSON?

Instead of creating a vue component that is only JSON, Create a JSON object and export it

jsonInput.js

export const jsonInput = [
  { id: "1", title: "Mars" },
  { id: "2", title: "Venus" },
  { id: "3", title: "Pluto" }
];

Import the JSON object into your component

Planets.vue

<script>
    import {jsonInput } from './jsonInput';
    export default {
      data(){
          return {
              planets : jsonInput 
          }
       }
    }
</script>

Upvotes: -1

Related Questions