React项目中Fetch无法向后端传递参数

问题:React项目中使用fetch向后端传递数据,POST请求时,发现把参数装进一个对象传递,后端并不能获取到数据,拼接成字符串加在URL中传递也不行(当然,GET请求可以)

解决:使用FormData传递参数

let formData = new FormData();

formData.append('name', 'kong');

formData.append('age', '18');

fetch(url, {method: 'POST', body: formData})...

例子:封装的一个请求Fetch的类

import Config from './config.js';

class Fetch extends Config{
	
	constructor(url, params, successFunc, errorFunc){
		super();
		this.url = super()._URL + url;
		this.params = params;
		this.successFunc = successFunc;
		this.errorFunc = errorFunc;
	}

	//发送GET请求
	getFetch(){
		var that = this;
		var str = '';
		if(typeof that.params === 'object' && that.params){
			str += '?';
			Object.keys(that.params).forEach(function(val){
				str += val + '=' + encodeURIComponent(that.params[val]) + '&';
			})
		}
		fetch(this.url + str, {
			method : 'GET'
		}).then(function(res){
			if(res.ok){
				res.json().then(function(data){
					that.successFunc(data);
				})
			}else if(res.status === 401){
				console.log('请求失败');
				that.errorFunc();
			}
		}, function(e){
			console.log('请求失败');
			that.errorFunc();
		})
	}
	
	//发送POST请求
	postFetch(){
		var that = this;
		var formData = new FormData();
		for(let k in that.params){
			formData.append(k, that.params[k]);
		}
		formData.append('oper_id', '11');
		formData.append('oper_name', 'kong');
		fetch(this.url, {
			method : 'POST',
			mode : 'cors',
			body : formData
		}).then(function(res){
			if(res.ok){
				res.json().then(function(data){
					that.successFunc(data);
				})
			}else{
				console.log('请求失败');
				that.errorFunc();
			}
		}, function(e){
			console.log('请求失败');
			that.errorFunc();
		})
	}
}

export default Fetch;
参考链接:

http://blog.csdn.net/yueaini10000/article/details/52597661

https://github.com/github/fetch

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值