最近自己弄个博客站点,前台用的React,服务器用的是node实现的,node是第一次接触,所以还在摸索,这篇mark下通信时遇到的坑。
fetch配置:
window.fetchUtility = function (options, errorFun) {
var request = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
// 'Accept': 'application/json'
// },
cache: 'no-store',
body:`userName=${options.data.userName}&password=${options.data.password}`
};
if (request.method.toLowerCase() === "get") {
request.body = null;
}
return fetch(options.url, request)
.then(function (response) {
if (response.ok) {
if (request.download) {
return response;
}
else {
return response.text().then(function (dataString) {
return {
responseStatus: response.status,
responseString: dataString,
isParseJson: request.isParseJson,
isPassStatus: request.isPassStatus
};
});
}
} else {
if (response.status == 403) {
window.location.href = "/error/" + response.status;
} else if (response.status == 409) {
// for simulation
$$.alert(true, { type: "w", content: "Sorry, currently you are in simulation mode and limited to read only access." });
throw new Error("simulation");
}
else {
if (errorFun) {
errorFun(response);
}
else {
throw new Error(response.statusText);
}
}
}
}).then(function (fetchResult) { if (request.download) { return fetchResult }; var queryResult = null; try {
if (!fetchResult.responseString) {
return null;
}
if (fetchResult.isParseJson && fetchResult.responseString) {
if ($.isEmptyObject(fetchResult.responseString)) {
queryResult = "";
} else {
queryResult = JSON.parse(fetchResult.responseString);
if (fetchResult.isPassStatus) {
queryResult[FetchResponsePropName.status] = fetchResult.responseStatus;
}
}
} else {
queryResult = fetchResult.responseString;
}
}
catch (ex) {
$$.error("An error happened while fetching information. Error:", ex);
}
return queryResult;
});
};
GET通信使用:
retrieve(){
let option = {
url: `./api/about/getAbout?test=${'dqhan'}`,
method:'Get'
}
fetchUtility(option).then(res=>{
var a = res;
}).catch(e=>{
console.log(e);
})
}
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~