程序员

Fetch的基本使用

2020-04-07  本文已影响0人  胡小喵_

[TOC]

1. 使用 fetch

1. 安装

npm install whatwg-fetch --save
import 'whatwg-fetch'

2. 基本使用

fetch 是全局变量 window 的一个方法,第一个参数是 URL

fetch('/some/url', {
    method: 'get'
}).then(dunction(response) {
        
}).catch(function(err) {
    
});

1. 发送 get 请求

fetch('/some/url?name=zhangsan&password=123', {
    method: 'get'
}).then(dunction(response) {
        
}).catch(function(err) {
    
});

数据拼接在url中

1. 发送 post 请求

fetch('/some/url', {
    method: 'post',
    headers: {
        'Content-Type': 'application/x-www/form-urlencoded'
    },
    body:`?name=zhangsan&password=123'`,  
    mode:
}).then(dunction(response) {
        
}).catch(function(err) {
    
});

3. 强制带Cookie

默认情况下,fetch 不会从服务端发送或接收任何 cookies,如果站点依赖于维护一个用户会话,则导致未经认证的请求(要发送 cookies,必须发送凭据头)。

2. Response 简介

Response 代表响应, fetch 的 then 方法接收一个 Response 实例。

// fetch 的 then 会传入一个 Response 对象
fetch('/')
    .then(function(res) {
        console.log('status: ', res);
    });

Response 提供的方法如下:

3. 参考资料

上一篇 下一篇

猜你喜欢

热点阅读