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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章