Express框架Fetch通信
最近自己弄个博客站点,前台用的React,服务器用的是node实现的,node是第一次接触,所以还在摸索,这篇mark下通信时遇到的坑。
fetch配置:
1 window.fetchUtility = function (options, errorFun) { 2 var request = { 3 method: 'POST', 4 headers: { 5 'Content-Type': 'application/x-www-form-urlencoded' 6 }, 7 // headers: { 8 // 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 9 // 'Accept': 'application/json' 10 // }, 11 cache: 'no-store', 12 body:`userName=${options.data.userName}&password=${options.data.password}` 13 }; 14 if (request.method.toLowerCase() === "get") { 15 request.body = null; 16 } 17 return fetch(options.url, request) 18 .then(function (response) { 19 if (response.ok) { 20 if (request.download) { 21 return response; 22 } 23 else { 24 return response.text().then(function (dataString) { 25 return { 26 responseStatus: response.status, 27 responseString: dataString, 28 isParseJson: request.isParseJson, 29 isPassStatus: request.isPassStatus 30 }; 31 }); 32 } 33 } else { 34 if (response.status == 403) { 35 window.location.href = "/error/" + response.status; 36 } else if (response.status == 409) { 37 // for simulation 38 $$.alert(true, { type: "w", content: "Sorry, currently you are in simulation mode and limited to read only access." }); 39 throw new Error("simulation"); 40 } 41 else { 42 if (errorFun) { 43 errorFun(response); 44 } 45 else { 46 throw new Error(response.statusText); 47 } 48 } 49 } 50 }).then(function (fetchResult) { 51 52 if (request.download) { return fetchResult }; 53 54 var queryResult = null; 55 56 try { 57 if (!fetchResult.responseString) { 58 return null; 59 } 60 if (fetchResult.isParseJson && fetchResult.responseString) { 61 if ($.isEmptyObject(fetchResult.responseString)) { 62 queryResult = ""; 63 } else { 64 queryResult = JSON.parse(fetchResult.responseString); 65 if (fetchResult.isPassStatus) { 66 queryResult[FetchResponsePropName.status] = fetchResult.responseStatus; 67 } 68 } 69 } else { 70 queryResult = fetchResult.responseString; 71 } 72 } 73 catch (ex) { 74 $$.error("An error happened while fetching information. Error:", ex); 75 } 76 return queryResult; 77 }); 78 };
GET通信使用:
1 retrieve(){ 2 let option = { 3 url: `./api/about/getAbout?test=${'dqhan'}`, 4 method:'Get' 5 } 6 fetchUtility(option).then(res=>{ 7 var a = res; 8 }).catch(e=>{ 9 console.log(e); 10 }) 11 }
express接受参数形式:
POST通信:
postRequest() { let data = { params: { test: 'test' } }; let option = { url: `./api/about/postRequest`, method: 'Post', data: data } fetchUtility(option).then(res => { var a = res; }).catch(e => { console.log(e); }) }
因为调试过程中express中接受参数时一直接收不到,所以mark下(node小白,正在努力ヾ(◍°∇°◍)ノ゙)
问题原因:
对node的不熟悉,以及对fetch的不精通。
前后台通信数据传递最基本的结构:
- header定义发送、接受的媒体类型
- 请求方式post、get等等
- body参数结构
以上三点是最基本的参数,然而我一直在纠结是不是还有什么配置错误,于是一直在这里打转转。
问题根本原因是需要在node里面使用body-parser来接受参数,这样express才能解析通信发过来的参数。
解决方法:
var bodyParser = require('body-parser'); const app = new express(); app.use(bodyParser.urlencoded({extended: true}))
总结:
我应该好好看看node的文档。sorry~