在Vue中获取api后,控制台日志未定义

问题描述 投票:0回答:3

从API获取(第三方,我在Laravel控制器中进行身份验证并获取数据)时,我在控制台中得到“未定义”。我想将数据存储在Vue组件中。

我尝试了很多不同的东西,包括get而不是fetch,但这也记录了undefined。我做了一些研究并阅读了箭头功能,但我没有使用箭头功能。

data() {
    return {
        tickets: [],
    };
},

created() {
    this.fetchTickets();
},

methods: {
    fetchTickets() {
        fetch('/api')
        .then(res => {
            this.tickets = res.json;
        })
        .then(res => {
            console.log(res.json);
        }) 
    }
}

所以,我想要的是我发送给PHP的第三方API的get请求集合,该请求返回到路由/ api,存储在我的Vue组件中。现在它只是记录未定义。

用PHP编辑后端请求

 $response = $client->get('v1/tickets/search.json', [
        'query' => ['statuses[]' => 'active', 'assignedTo[]' => 314955, 
        'sortDir' => 'desc', 'sortBy' => 'updatedAt']
    ]);

    $json = (string)$response->getBody()->getContents();
    $decoded = json_decode($json, true);
    return collect($decoded);

路线:Route :: get('/ api','ApiController @ getTickets',);

javascript vue.js
3个回答
2
投票

fetch返回包含响应res的承诺。 (这只是一个HTTP响应,而不是实际的JSON。)

要从响应中提取JSON正文内容,我们使用json()方法

您可以阅读更多关于using fetch的信息。

fetchTickets() {
    fetch('/api')
    .then(res => res.json()) //returning a promise To extract the JSON body content from the response
    .then(resJson => {
        this.tickets = resJson
        console.log(resJson);
    }) 
}

1
投票

在进入第二个承诺之前返回您的数据。

fetchTickets() {
    fetch('/api')
    .then(res => {
        this.tickets = res.json;
        return res;
    })
    .then(res => {
        console.log(res.json);
    }); 

1
投票

在第一个promise中添加return语句

fetch('/api')
  .then(res => {
      return res.json();
   })
   .then(tickets => {
     // tickets is a local variable scoped only here
     console.log(tickets);
   }) 
© www.soinside.com 2019 - 2024. All rights reserved.