搭建简易的服务器:
①新建express文件夹
②终端中执行 express -e 和 npm i
③在express/routes/user.js中定义login请求路径
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
var express = require('express') var router = express.Router() router.get('/login', (req, res) => { let { username, password } = req.query console.log(username, password) if (username === 'admin' && password === 'admin') { res.json({ code: 200, data: 'OK' }) } else { res.json({ code: 200, data: { info: '用户名或密码错误' } }) } }) router.post('/login', (req, res) => { let { username, password } = req.body console.log(username, password) if (username === 'admin' && password === 'admin') { res.json({ code: 200, data: 'OK' }) } else { res.json({ code: 200, data: { info: '用户名或密码错误' } }) } }) module.exports = router
④dev.config.js中配置跨域代理
⑤package.json中用supervisor替换原来的node,重启服务:npm start
"scripts": { "start": "supervisor ./bin/www" },
react中使用fetch:
①下载插件:npm i whatwg-fetch
②组件中引入和使用
import { fetch as fetchPolyfill } from 'whatwg-fetch' // 起一个别名,防止和原生的fetch冲突
fetch的第一个then方法中返回结果集,需要在这里对数据进行处理,设置希望返回的数据类型
componentDidMount() { fetchPolyfill('/users/login?username=admin&password=admin') .then((res) => res.json()) .then((data) => { console.log(data) // 这儿的data就是 express 中 res.json() 中的对象 }) }
post请求:需要下载qs依赖,post请求需要设置method和headers,body参数需要用qs模块转为查询字符串
fetchPolyfill('/users/login', { method: 'post', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: qs.stringify({ username: 'admin', password: 'admin' }) }) .then((res) => res.json()) .then((data) => { console.log(data) })
fetch封装:
1、src下新建utils/requset.js:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import { fetch as fetchPolyfill } from 'whatwg-fetch' import qs from 'qs' const get = (options) => { let str = '', path = '' if (options.data) { for (let key in options.data) { str += `&${key}=${options.data[key]}` } } path = options.url + '?' + str.slice(1) return fetchPolyfill(path, { headers: { ...options.headers, 'content-type': 'application-json' }, credentials: 'include' }).then((res) => res.json()) } const post = (options) => { return fetchPolyfill(options.url, { method: 'post', headers: { ...options.headers, 'content-type': 'application/x-www-form-urlencoded' }, credentials: 'include', body: qs.stringify(options.data) }).then((res) => res.json()) } export default { get, post }
2、引入和使用
import request from './utils/request' async componentDidMount() { let res = await request.get({ url: '/users/login', data: { username: 'admin', password: 'admin' } }) console.log(res, 'get') request .post({ url: '/users/login', data: { username: 'admin', password: 'admin' } }) .then((data) => { console.log(data, 'post') }) }
fetch的特点:
1、返回promise
2、留给开发者足够的操作空间,可以自定义返回的数据类型:json、text、blob、arrayBuffer...
3、fetch处理成果后不是直接将结果返回,第一个then方法中返回一个未处理的结果集,在这里解析数据,第二个then方法中获取数据
4、默认不会携带cookie,需要设置 credentials: 'include'