Dva & get请求 & post请求

Dva

https://dvajs.com/

安装

npm install dva-cli -g

dva new dva-quickstart
cd dva-quickstart
npm start

路由

//新建route页面, routes/Products.js,内容如下:
import React, { Component } from 'react';
export default class Products extends Component{
    render(){
        return (
            <h2>List of Products</h2>
        )
    }
}

//添加路由信息到路由表,编辑 router.js :
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import Products from './routes/Products';     					//导入Products页面
import 'antd/dist/antd.css';

function RouterConfig({ history }) {
  return (
    <Router history={history}> 
      <Switch>
		<Route path="/products" exact component={Products} />	//设置Products页面路由
      </Switch>
    </Router>
  );
}

export default RouterConfig;

组件仓库数据通信

//第一步:定义Model,在models文件中新建model, models/products.js 
export default {
  namespace: 'products',				//namespace 表示在全局 state 上的 key
  state: {
    name: 'Apple',
    songName: '爱情错觉'
  },
  effects: {},
  reducers: {							//接收 action,同步更新 state
    setSongName(state, action) {
      return {
        ...state,
        songName: action.payload.value
      }
    }
  }
}


//第二步:在 index.js 里载入他
app.model(require('./models/products').default);


//第三步:组件关联仓库(例如组件Xcontent)
import React, { Component } from 'react';
import { connect } from 'dva';

const namespaced = 'products';
const Xcontent = class Xcontent extends Component {
	constructor(props) {
		super(props);
		this.state = {}
	}
	
	updateSongName = () => {			//dispatch触发action
		const { dispatch } = this.props;
		dispatch({
			type: `${namespaced}/setSongName`,
			payload: {
				value: '余情未了'
			}
		})
	}

	render() {
		const { products } = this.props;
		return (
			<div>
				<p>{products.songName}</p>
				<button onClick={this.updateSongName}>点我修改歌名</button>
			</div>
		)
	}
}

function mapPropsState({ products }) {
	return { products }
}
export default connect(mapPropsState)(Xcontent);

配合后端egg.js框架

get请求
//前端get请求
demand() {
    request('http://localhost:7001/dss?username=llt&id=5').then((res) => {
        console.log(res);
    })
}

//后端响应
//router.js文件配置路由
router.get('/dss', controller.home.dss);

//home.js文件配置路由映射方法
async dss() {
    const { ctx } = this;
    const { username, id } = ctx.request.query;
    console.log(username, id);
    
    //后端返回数据格式最好为对象或数组
    ctx.body = {
        key : '6666'
    }
}
post请求
//前端post请求
request('http://localhost:7001/find', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
    body: JSON.stringify({
        // 参数名:参数
        username: "llt",
        password: "111"
    }),
    credentials: 'include'		//是否携带cookie,默认为omit不携带; same-origi同源携带; include同源跨域都携带
    
}).then((res) => {
    console.log(res);
})


//后端响应
//router.js文件配置路由
router.post('/finds', controller.home.find);

//home.js文件配置路由映射方法
async find() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;
    console.log(username, password);
    
    //后端返回数据格式必须为对象或数组
    ctx.body = {        
        key: 'llt'
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
dva中,我们可以通过封装request方法来对http请求进行进一步的封装,使其更加方便和易用。 一种常见的做法是封装一个request工具函数,该函数会返回一个Promise对象,我们可以在models中的effect中使用该函数来发送网络请求。该函数可以包含一些自定义的配置参数,例如请求method、请求头、请求体等。 以下是一个基于dva的http请求封装示例代码: ```javascript import request from 'umi-request'; function http(url, options) { return request(url, options) .then(response => { if (response && response.status === 200) { return response.data; } else { throw new Error('请求失败'); } }) .catch(error => { console.error(error); throw error; }); } export default http; ``` 在上面的代码中,我们封装了一个http函数,该函数接收两个参数,分别为url和options。这两个参数与request函数的参数一致。我们使用request函数发送网络请求,并在then方法中判断请求是否成功。如果成功,我们会将请求结果返回;如果失败,我们会抛出一个错误。 在使用http函数时,我们可以通过传入options参数来自定义请求配置,例如: ```javascript http('/api/data', { method: 'post', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'test', age: 20 }) }) .then(data => { console.log(data); }) .catch(error => { console.error(error); }); ``` 在上面的代码中,我们通过传入options参数来自定义请求的method、headers和body。如果请求成功,我们会在then方法中打印请求结果;如果请求失败,我们会在catch方法中打印错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值