使用fetch
小于 1 分钟
使用fetch
使用方法
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
<button onclick='fun1()'>点击我 1</button>
function fun1(){
fetch('http://httpbin.org/get',{mode:'no-cors'})
.then(response => response.json())
.then(data => console.log(data));
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>element-plus</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/element-plus/dist/index.css"
/>
<meta http-equiv="Access-Control-Allow-Origin" content="*" />
<link
rel="stylesheet"
href="https://unpkg.com/element-plus/dist/index.css"
/>
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios"></script>
<script src="https://unpkg.com/element-plus"></script>
</head>
<body>
<div id="app">
<el-button type="primary" @click="showMsg">element-plus</el-button>
<div>{{msg1}}</div>
<el-button type="primary" @click="showAxios">获取标签</el-button>
<div>{{msg2}}</div>
</div>
<script>
axios.defaults.crossDomain = true;
const app = Vue.createApp({
data() {
return {
msg: "hhhhh",
msg1: "",
msg2: "",
};
},
methods: {
async showAxios() {
let data = await axios.get(
"https://www.jianshu.com/shakespeare/v2/notes/recommend",
{
headers: {
"Access-Control-Allow-Headers": "Access-Control-Allow-Origin",
"Access-Control-Allow-Origin": "*",
},
}
);
this.msg2 = data;
setTimeout(() => {
this.msg2 = "";
}, 5000);
},
showMsg() {
fetch(
"https://118.89.204.198/resolv?host=www.zhihu.com&os_type=web",
{
method: "GET",
mode: "cors",
headers: {},
}
)
.then((res) => {
console.log(res);
return res.json();
})
.then((data) => {
this.msg1 = data;
setTimeout(() => {
this.msg1 = "";
}, 4000);
})
.catch((error) => {
console.error("Error:", error);
});
},
},
});
app.use(ElementPlus);
app.mount("#app");
// 使用setup
// const { createApp, reactive, toRefs } = Vue;
// const data = reactive({
// state: 12,
// });
// const app = createApp({
// setup() {
// return {
// ...toRefs(data),
// };
// },
// });
// app.mount("#app");
</script>
</body>
</html>