Skip to content

Instantly share code, notes, and snippets.

@crlspe
Created December 23, 2022 03:50
Show Gist options
  • Save crlspe/3de6371564fb85b299b7d9f2f11cd842 to your computer and use it in GitHub Desktop.
Save crlspe/3de6371564fb85b299b7d9f2f11cd842 to your computer and use it in GitHub Desktop.
function post(opts, data, sucFn, errFn, type) {
var postDataStr = JSON.stringify(data);
console.log('=== postDataStr ===', postDataStr);
var optsPost = {
hostname: opts.host,
port: opts.port ? opts.port : 80,
path: opts.path,
method: (type || 'POST'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postDataStr.length
},
body: postDataStr
};
console.log(optsPost);
let reqPost = http.request(optsPost, function (resPost) {
resPost.setEncoding('utf8');
let rawData = '';
resPost.on('data', chunk => {
console.log(`BODY: ${chunk}`);
if (typeof chunk === 'object') {
chunk = JSON.stringify(chunk);
}
rawData += chunk;
});
resPost.on('end', () => {
console.log('== rawData ==', rawData);
try {
rawData = (typeof rawData === 'string') ? JSON.parse(rawData) : rawData;
if (rawData.status === 0 || rawData.errno === 0 || rawData.code === 1000) {
sucFn && sucFn(rawData.data);
} else {
errFn && errFn('操作失败');
}
} catch (e) {
errFn && errFn('结果返回错误');
}
console.log('No more data in response.');
});
});
reqPost.on('error', function (e) {
errFn && errFn(e);
console.log(`problem with request: ${e.message}`);
});
// 发送REST请求时传入JSON数据
reqPost.write(postDataStr);
reqPost.end();
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment