stenciljs 中的 http 请求 [英] http requests in stenciljs
问题描述
如何在 StencilJS 中发出 http 请求(GET/POST/PUT/DELETE)?
How can I make http requests (GET / POST / PUT / DELETE) in StencilJS?
我尝试使用 axios 如下:npm install axios --save
并在模板组件 import axios from 'axios';
.一旦我调用 axios.get(...)
我收到以下错误消息:
I tried using axios as follows: Did npm install axios --save
and in the stencil component import axios from 'axios';
. As soon as I call axios.get(...)
I get the following error message:
[ 错误 ] 捆绑:node_modules/axios/lib/adapters/http.js,第 4 行
[ ERROR ] bundling: node_modules/axios/lib/adapters/http.js, line: 4
模块不能自己导入
L3: var utils = require('./../utils');
L3: var utils = require('./../utils');
L4: var set = require('./../core/settle');
L4: var settle = require('./../core/settle');
L5: var buildURL = require('./../helpers/buildURL');
L5: var buildURL = require('./../helpers/buildURL');
我知道这可能与这个问题有关:https://github.com/ionic-team/stencil/issues/98
I understand it might have to do with this issue: https://github.com/ionic-team/stencil/issues/98
但是,关于如何在模板组件中获取 html 请求的任何建议?
However, any recommendations on how to get html requests work within a stencil component?
推荐答案
我们可以使用 fetch
API.它是浏览器原生的,因此不需要导入.StencilJS 也有一个 polyfill,所以它适用于任何地方.
We can use the fetch
API. It is browser native and does therefore not need an import. StencilJS also has a polyfill for it, so it works everywhere.
感谢@insanicae 为我指明方向.
Thanks to @insanicae for pointing me to it.
示例:
import { Component, State } from '@stencil/core';
@Component({
tag: 'app-profile',
styleUrl: 'app-profile.css'
})
export class AppProfile {
@State() name: string;
componentWillLoad() {
fetch('https://api.github.com/users/ErvinLlojku')
.then((response: Response) => response.json())
.then(response => {
this.name = response['name'];
});
}
render() {
return [
<ion-header>
<ion-toolbar color="primary">
<ion-buttons slot="start">
<ion-back-button defaultHref="/" />
</ion-buttons>
<ion-title>Profile: {this.name}</ion-title>
</ion-toolbar>
</ion-header>,
<ion-content padding>
<p>My name is {this.name}.</p>
</ion-content>
];
}
}
有关更多信息,请参阅 fetch 的官方文档.https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Consult official docs of fetch for more. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
这篇关于stenciljs 中的 http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!