fetch交互+fetch-jsonp

954 阅读2分钟

我们前端属性的交互技术有很多例如 XMLHttpRequest jquery、zepto(jq怎么写他怎么写)axios等等,我们下面简单的讲一下fetch的使用,fetch相当于XMLHttp的加强版,原生js

1优点:

01:一是接口合理化,AJAX 是将所有不同性质的接口都放在 XHR 对象上,而Fetch是将它们分散在几个不同的对象上,设计更合理;

02:二是Fetch操作返回 Promise 对象,避免了嵌套的回调函数。

2基础用法:

fetch(url,option)
    .then(function(response) {
    return response.json();
    })
    .then(function(myJson) {
    console.log(myJson);
    });

01option为前端的参数配置,如请求方式,herder,body等

 method   '' get|post
 headers   {
       'content-type:application'
           'token'
            }
 body: JSON.stringify(data)  这里面写的是json对象,headers必须匹配

02第一个.then不是接收数据用的,是用来设置后台给前端返回的数据类型

  return response.json();   //返回的数据是json格式

03第二个.then才是返回的数据

04 .cath是错误执行时的代码

下面为登录fetch接口交互案例:

import {useState} from 'react'export default function () {
    let [user,SetUser]=useState({user:'',pass:''});
    let change=(ev)=>{
        var json={...user};
        json[ev.target.name]=ev.target.value;
        SetUser(json);
    };
    let login=()=>{
        /*fetch(`/api/login?userName=${user.user}&passWord=${user.pass}`)
        .then(function(response) {
            return response.json();
        })
        .then(function(myJson) {
            console.log(myJson);
        });*/
        /*fetch('/api/register',{
            method:'POST', 
           body:JSON.stringify({ 
               userName:user.user,
               passWord:user.pass
            }),
            headers: {
                'content-type': 'application/json'
            },
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(myJson) {
            console.log(myJson);
        });*/    };
    return (
        <div id="div1"> 
           用户名<input name="user" onChange={change} type="text" value={user.user}/><br/>
            密码:<input name="pass" onChange={change} type="password" value={user.pass}/>
           <button onClick={login}>登录</button>
        </div>
    )
};

说到这里,我们顺便谈一下跨域访问的配置代理方法,由于前端存在安全问题,所以有了同源策略,即协议+域名+端口号有一个不一致就会出现跨域问题,那么我们解决跨域的问题大概有三种,

1配置代理,以react单页面项目为例

01首先我们需要在控制台yarn/npm eject   作者把webpack的文件隐藏了。 把webpack的配置文件拷贝一份 暴露出来

02 config文件夹中找到webpackDevServer配置文件

03 配置proxy项

proxy:{
          "/api":{
            target:"http://172.16.14.48:4321",
            changeOrigin:true,
            pathRewrite:{
              "^/api":""
            }
          }
        }

2 jsonp跨域方法

01 jsonp需要前后台配合处理,

02 jsonp的原理:

利用html中script标签不参与同源策略,动态的创建script标签。在全局定义全局函数,用来接收script标签引过来的js文件中的函数调用传过来的数据

注释:html没有同源策略,例如图片的src,cdn方式引入的script标签,link引入的其他代码等(但因为script,link等标签页面加载的时候,只加载一遍,所以需要动态添加)

注意:

fetch是没有jsonp的写法的,我们需要下载fetch-jsonp模块引入

npm install fetch-jsonp

  fetch-jsonp的写法和fetch类似,例如下面调用百度搜索的接口

import fetchJsonp from 'fetch-jsonp'export default function () {
    let send=()=>{
        fetchJsonp(`https://www.baidu.com/sugrec?pre=1&ie=utf-8&json=1&prod=pc&from=pc_web,22160&wd=赘婿`,{
            jsonpCallback: 'cb',
        })
           .then(function(response) {
                return response.json()
          }).then(function(json) {
            console.log(json)
          }).catch(function(ex) {
           console.log('parsing failed', ex)
        })
    };
    return (
        <div>
            <button onClick={send}>点击</button>
        </div>
    )
}

3:cors跨域

需要后台处理,等同给所有接口放开,设置相应请求头,让所有请求通过