使用fetch,fetch各位自行了解。
1.封裝Fetch函數
首先在src目錄下新建public文件夾。文件夾下新建utils.js文件,里面配置一些公共函數。
/**
* 封裝fetch請求
*/
// 全局路徑
const commonUrl = 'http://www.XX.com:8001'
const parseJSON = function (response) {
return response.json();
};
const checkStatus = function (response) {
if (response.status >= 200 && response.status < 500){
return response;
}
const error = new Error(response.statusText)
error.response = response
throw error;
};
// eslint-disable-next-line require-jsdoc
export default function request (options = {}) {
const {data, url} = options
options = {...options}
// 跨域
options.mode = 'cors'
delete options.url
if (data) {
delete options.data
options.body = JSON.stringify({
data
});
}
options.headers = {
'Content-Type': 'application/json'
}
return fetch(commonUrl + url, options, {credentials: 'include'})
.then(checkStatus)
.then(parseJSON)
.catch(err => ({err}));
}
這里可以自行百度fetch封裝,我只是為了配合上篇文章才這么寫的。
2.去調用Fetch函數
(1)在components/login/submit-login-button.jsx文件下添加 myFunction函數,想寫es6可以自行修改,
(注1)這里為了實例所以沒用全局變量,想標准一些可以去 webpack.config.js文件添加如下代碼,怎么用自行查詢理解一下,總之就是全局變量的問題
devServer: {
contentBase: path.resolve(__dirname, 'build'),
host: '0.0.0.0',
port: process.env.PORT || 8601,
proxy: [{
context: ['/api/**', '**'],
target: '你的API地址',
changeOrigin: true,
secure: false
}]
},
(注2)login/submit-login-button.jsx文件看上篇博文(如果更新了的話)
引入方法如下
import {parseJSON, checkStatus} from '../../public/utils.js';
這里用了三種fetch方法,我是隨便用的,都是一個意思,第三種用的是自行封裝的函數
const myFunction = function (){
// eslint-disable-next-line no-console
console.log('登錄!');
// ------ 方法一 -------
// const url = '/Login/(你的API接口url)';
// fetch(url,{
// method: 'post',
// mode: 'cors',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify({
// password: '1234567',
// username: 'y3',
// tel:'1322222233'
// })
// }).then(response=>response.json())
// .then(data=>console.log(data))
// .catch(e=>console.log('error' + e))
// ------ 方法二 -------
const commonUrl = '你的API接口地址';
const options = {};
const url = commonUrl + '/Login/(你的API接口url)';
const data = {
'password': '1234567',
'username': 'yang',
'tel': '13848324733'
}
options.method = 'post'
options.mode = 'cors'
options.body = JSON.stringify(data)
options.headers = {
'Content-Type': 'application/json'
}
return fetch(url,options,{credentials:'include'})
.then(checkStatus)
.then(parseJSON)
.then((res) => {
// if (res.retCode === '0001'){
// localStorage.setItem('x-access-token',res.retBody.AccessToken)
// return 'success';
// } else if (res.retCode === '0002'){
// return 'error';
// } else if (res.retCode === '0003'){
// return 'error';
// } else {
// return;
// }
})
.catch(err=>({err}))
// --------- 方法三 ---------
// request({
// url: '(你的API接口具體的url)',
// method: 'post',
// mode: 'cors',
// data: {
// Header: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'},
// Body: JSON.stringify({
// password: '1234567', username: 'y3', tel: '13843322123'
// })
// }
// }) .then (function(response) {
// return response.json()
// }).then (function(json) {
// console.log('parsed json', json)
// }).catch(function(ex) {
// console.log('parsing failed', ex)
// })
}
使用的是post請求,配置跨域,body傳遞的數據全部轉為json
options.method = 'post'
options.mode = 'no-cors'
options.body = JSON.stringify(data)
options.headers = {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
(2)修改下方onClick,添加剛寫的myFunction方法
SubmitLoginButton.defaultProps = {
onClick: () => {
myFunction();
}
};
(3)去試試
點擊登錄,


搞定!
可能遇到的問題:
跨域,下篇文章會介紹
已更新:https://www.cnblogs.com/mryaohu/p/12483757.html
