以前写数据接口,对接请求都是使用的Ajax,或者Axios之类的,最近在使用React进行开发,用到了fetch, 和querystring
import qs from 'querystring'
<!-- get请求 -->
fetch("http://iwenwiki.com/api/blueberrypai/getChengpinInfo.php")
.then(res => res.json())
.then(data => {
console.log(data)
})
<!-- post请求 -->
fetch("http://iwenwiki.com/api/blueberrypai/login.php", {
method: 'POST' , // 请求方式
headers: { // 请求头
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/plain, */*',
},
<!-- body: "user_id=iwen@qq.com&password=iwen123&verification_code=crfvw" -->
<!-- 此处传参使用字符串传参的方式,所以需要参数间 & 分隔拼串 -->
<!-- 如果不想写拼串,也可以直接引入 querystring来进行转换操作如下 -->
body: qs.stringify({
'user_id': 'iwen@qq.com',
'password': 'iwen123',
'verification_code': 'crfvw'
})
})
跨域的解决方案
跨域一般分为两种场景: 开发环境下的跨域问题和生产环境下的跨域问题
此处以React项目开发环境下为例
componentDidMount() {
fetch("http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0")
.then(res => res.json())
.then(data => {
console.log(data)
})
.catch(error => {
console.log(new Error(error))
})
}
此处请求会跨域
需要在 package.json 文件中配置 proxy 代理解决
配置完成 package.json 文件后需要将请求接口前面的已经被代理的地址去掉如下
componentDidMount() {
fetch("/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0")
.then(res => res.json())
.then(data => {
console.log(data)
})
.catch(error => {
console.log(new Error(error))
})
}
然后终止此项目进程,重新运行该项目即可使用代理解决跨域问题。打开浏览器调试,接口数据正常请求得到。
fetch 封装常用请求
工具类文件utils下创建 http.js 用于封装常用的请求方法
import qs from 'querystring'
<!-- 导出封装的 get 请求 -->
export function httpGet(url) {
const result = fetch(url)
return result
}
<!-- 导出封装的 post 请求 -->
export function httpPost(url, params) {
<!-- params为post请求携带参数 -->
const result = fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/plain, */*',
},
body: qs.stringify(params)
})
}
然后在 utils 同级创建一个 api 文件,用于管理接口,api 下新建一个 base.js ,用于向外暴露接口的前置接口地址公共部分(一般情况下接口地址的前半部分是一致的),然后新建一个 index.js 用于定义业务接口请求统一管理,或者创建不同的功能分类 (如,登录的接口单独写在一个文件里,首页的接口单独写在一个文件里,便于维护)
base.js
const base = {
baseUrl: 'http://iwenwiki.com/api'
}
index.js
import {httpGet, httpPost} from '../utils/http'
import base from './base'
<!-- 在下面定义各种业务接口 -->
const api = {
<!-- get请求 -->
getUserId() {
return httpGet(base.baseUrl + '/blueberrypai/getChengpinInfo.php');
},
<!-- post请求 -->
getLogin(params) {
return httpPost(baseUrl + '/blueberrypai/login.php', params);
}
}
<!-- 定义完成后导出 api ,在需要调用处导入调用即可 -->
export default api
调用接口的文件下
import api from '../api'
<!-- get请求不用携带参数,直接获取并打印数据 -->
api.getUserId().then(res => res.json()).then(data => {
console.log(data)
})
<!-- post请求调用接口时传入参数,获取并打印数据 -->
api.getLogin({
'user_id': 'iwen@qq.com',
'password': 'iwen123',
'verification_code': 'crfvw'
}).then(res => res.json()).then(data => {
console.log(data)
})
请到客户端“主题--自定义配置--valine”中填入ID和KEY