M Muqiit Faturrahman
M Muqiit Faturrahman

Reputation: 129

Cannot get the data from axios with api - vue js

I have an issue when i get the data with vue js, it returns a HTML not json. I conse the route params it show an id of the post. This is my code in vue:

axios.get("api/posts/" + this.$route.params.id).then(response => {
  console.log(this.$route.params.id);
  console.log(response.data);
});

And this is the response data :

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <link rel="stylesheet" href="http://127.0.0.1:8000/css/app.css">
        <script src="http://127.0.0.1:8000/js/app.js" defer></script>
    </head>
    <body>
        <div id="app">
            <index></index>
        </div>
    </body>
</html>

But in the postman, i access the url "api/posts/1" it show json data {"id": 1,"title": "Schambergerstad Fancy Rooms", "description": "Qui minima tempora ea modi maiores. Quaerat non aut porro vel occaecati. Deleniti quaerat quod veniam. Dolor ducimus facilis molestiae omnis fuga occaecati.", "created_at": "2020-06-04T11:28:25.000000Z","updated_at": "2020-06-04T11:28:25.000000Z" }

But i see in network tab, the request url is "http://127.0.0.1:8000/posts/api/posts/1". Why become to that url? I call it in axios is "api/posts/1" How to fix it?

Upvotes: 0

Views: 1386

Answers (2)

LHJ
LHJ

Reputation: 692

try adding headers Content-Type json

axios.get("/api/posts/" + this.$route.params.id, {
    headers: {
        'Content-Type': 'application/json'
    }
}).then(response => {
  console.log(this.$route.params.id);
  console.log(response.data);
});

Upvotes: 2

M Muqiit Faturrahman
M Muqiit Faturrahman

Reputation: 129

Okay sorry it's just typo axios.get("api/posts/" + this.$route.params.id) it's should add "/" before "api/posts/"

axios.get("/api/posts/" + this.$route.params.id)

Upvotes: 0

Related Questions