gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:13:27 25 4
gpt4 key购买 nike

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

我尝试了很多不同的方法,包括使用 get 而不是 fetch,但这也记录为未定义。我做了一些研究并阅读了有关箭头函数的内容,但我没有使用箭头函数。

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

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

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

所以,我想要的是由我发送到 PHP 中的第 3 方 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);

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

最佳答案

fetch 返回一个包含响应 res 的 promise 。(这只是一个 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);
})
}

关于javascript - 在 Vue 中获取 api 后控制台日志未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55592624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com