【问题标题】:Cannot get the data from axios with api - vue js无法使用 api 从 axios 获取数据 - vue js
【发布时间】:2020-09-27 04:41:27
【问题描述】:

当我使用 vue js 获取数据时遇到问题,它返回的是 HTML 而不是 json。我认为它显示帖子的 id 的路线参数。这是我在 vue 中的代码:

axios.get("api/posts/" + this.$route.params.id).then(response => {
  console.log(this.$route.params.id);
  console.log(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>

但在邮递员中,我访问 url “api/posts/1” 它显示 json 数据 {"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” }

但我在网络选项卡中看到,请求 url 是“http://127.0.0.1:8000/posts/api/posts/1”。为什么变成那个网址?我在 axios 中称它为“api/posts/1” 如何解决?

【问题讨论】:

  • 你能给我们看看请求头吗?
  • 请求 URL:127.0.0.1:8000/posts/api/posts/1 请求方法:GET 状态码:200 OK 远程地址:127.0.0.1:8000 推荐人策略:no-referrer-when-downgrade
  • 接受:application/json, text/plain, / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,id ;q=0.8 连接:keep-alive 主机:127.0.0.1:8000 引用者:127.0.0.1:8000/posts/1

标签: javascript laravel api vue.js axios


【解决方案1】:

尝试添加标头 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);
});

【讨论】:

【解决方案2】:

好的,抱歉,这只是错字axios.get("api/posts/" + this.$route.params.id) 它应该在"api/posts/" 之前添加"/"

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

【讨论】:

    猜你喜欢
    • 2021-03-07
    • 2021-09-22
    • 2021-06-25
    • 2019-08-03
    • 2021-05-26
    • 2020-01-25
    • 2018-09-03
    • 2020-07-07
    • 2023-03-23
    相关资源
    最近更新 更多