github代码:https://github.com/aurora10/amazone-clone.git
我尝试利用Axios来访问API但出现错误:
控制台中的错误是NUXT SSR:
TypeError: Cannot read property '$get' of undefined
at asyncData (pages/index.js:98:35)
at promisify (server.js:1898:15)
at Promise.all.Components.map.Component (server.js:1573:82)
at Array.map (<anonymous>)
at module.exports../.nuxt/server.js.__webpack_exports__.default (server.js:1569:51)
这是我尝试做到的方式:
export default {
async asyncData({ $axios }) {
try {
let response = await $axios.$get("http://localhost:3000/api/products");
console.log(response);
return {
products: response.products
};
}catch (err) {
console.log(err);
}
}
}
API本身有效。如果我从浏览器中调用它-它会给我产品列表。 我究竟做错了什么?
完整填充:
<template>
<div class="container-fluid browsing-history">
<div class="row">
<div class="col-sm-8 col-8">
<h1 class="a-size-large a-spacing-none a-text-normal">All products</h1>
<div class="a-spacing-large"></div>
<a href="#" class="a-button-buy-again">Add new product</a>
<a href="#" class="a-button-history margin-right-10">Add new category</a>
<a href="#" class="a-button-buy-again margin-right-10">Add new owner</a>
</div>
</div>
</div>
<div class="a-spacing-large"></div>
<div class="container-fluid browsing-history">
<div class="row">
<div class="col-xl-2 col-lg-2 col-md-3 col-sm-6 col-6 br bb">
<div class="history-box">
<!-- product page-->
<a href="#" class="a-link-normal">
<img src="" class="img-fluid" alt="">
</a>
<div class="a-spacing-top-base asin-title">
<span class="a-text-normal">
<div class="p13n-sc-truncated">Title </div>
</span>
</div>
<div class="a-row">
<a href="#">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
</a>
<span class="a-letter-space"></span>
<span class="a-color-tertiary a-size-small asin-reviews">(1732)</span>
</div>
</div>
<!--price-->
<div class="a-row">
<span class="p13-sc-price">$25</span>
</div>
<!--byttons-->
<div class="a-row">
<a href="#" class="a-button-history margin-right-10">Update</a>
<a href="#" class="a-button-history margin-right-10">Delete</a>
</div>
</div>
</div>
</div>
导出默认值{ 异步asyncData({$ axios}){ 尝试{ let response =等待$ axios。$ get(“ http:// localhost:3000 / api / products”); console.log(response); 返回{ 产品:产品 }; } catch(err){ console.log(err); } } };
我确实确保已安装。我还包括了
module.exports = {
modules: [
'@nuxtjs/axios',
],
axios: {
// proxyHeaders: false
}
}
就像他们在安装手册中说的那样。还尝试在获取之前删除$ ...在控制台中仍然出现相同的错误:(我不知道还有什么错误。.
答案 0 :(得分:2)
您似乎未包含axios模块,请在此处https://axios.nuxtjs.org/setup.html#install
查看安装过程然后,您的配置在您的导出默认设置中应该是这样
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://bootstrap-vue.js.org
'bootstrap-vue/nuxt',
'@nuxtjs/axios'
],
axios: {
// proxyHeaders: false
}
答案 1 :(得分:0)
npm install @nuxtjs/axios
...
axios: {
// proxyHeaders: false
}
...
$
中的$axios.$get
。应该是$axios.get()