先后端交互是开发现代应用必不可少的内容,不一样于angular内置HttpClientModule
,react默认并未提供用于http请求的功能。咱们直接使用fetch,但一些老旧的浏览器支持度不太好。本文中,咱们推荐使用基于Promise
的库 -- axios。react
axios
的基本用法很是简单,跟jquery的ajax
相似。jquery
若是restful api
至于一个单独域名之下,且支持跨域。咱们能够对axios
进行自定义配置设置baseUrl
并封装。ios
// client.ts import axios from 'axios'; axios.defaults.baseURL = 'http://api.example.com'; export default axios;
使用时直接调用client.ts
便可:git
// 使用示例 import client from 'client.ts'; ... client.get('/api/v0/test') .then(response => { // handle response }) .catch(error => { // handle error }); ...
// client.ts import axios from 'axios'; // 请求头携带token axios.interceptors.request.use( (config) => { const storageCredential = localStorage.getItem('credentials'); const credentials = storageCredential ? JSON.parse(storageCredential) : null; if (credentials && credentials.access_token) { config.headers = { ...config.headers, Authorization: 'Bearer ' + credentials.access_token }; } return config; }, (error) => { return Promise.reject(error); } ); // 处理response axios.interceptors.response.use( (response) => { // success handle return response; }, (error) => { if (error.response && error.response.status === 401) { // 401 handle } return Promise.reject(error); }); export default axios;
proxy
设置通常状况下,react在开发环境下会启动一个dev server
,假设咱们此时又启动了一个api server
用于提供后端数据,那么就会涉及一个跨域的问题。为了解决跨域问题,咱们就须要进行代理配置。具体实现方式为,在package.json
里添加(以api server
端口号3000为例):github
/* package.json */ "proxy": { "/api": { "target": "http://localhost:3000", "secure": "false" } }
至此,先后端数据交互的内容完毕。ajax
react扬帆启航专栏分享的时我我的学习与实践react过程当中的一些历程,但愿借此专栏与你们共同探讨react相关的技术,以求进步。json