首页
登录 | 注册

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



2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.009 s.
京ICP备10005923号