uWebSockets.js/examples/JsonPost.js

73 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-02-20 22:19:30 +00:00
/* Simple example of getting JSON from a POST */
const uWS = require('../dist/uws.js');
const port = 9001;
const app = uWS./*SSL*/App({
key_file_name: 'misc/key.pem',
cert_file_name: 'misc/cert.pem',
passphrase: '1234'
}).post('/*', (res, req) => {
/* Note that you cannot read from req after returning from here */
let url = req.getUrl();
/* Read the body until done or error */
readJson(res, (obj) => {
console.log('Posted to ' + url + ': ');
console.log(obj);
res.end('Thanks for this json!');
}, () => {
2019-02-21 13:24:29 +00:00
/* Request was prematurely aborted or invalid or missing, stop reading */
console.log('Invalid JSON or no data at all!');
2019-02-20 22:19:30 +00:00
});
}).listen(port, (token) => {
if (token) {
console.log('Listening to port ' + port);
} else {
console.log('Failed to listen to port ' + port);
}
});
/* Helper function for reading a posted JSON body */
function readJson(res, cb, err) {
let buffer;
/* Register data cb */
res.onData((ab, isLast) => {
let chunk = Buffer.from(ab);
if (isLast) {
2019-02-21 13:24:29 +00:00
let json;
2019-02-20 22:19:30 +00:00
if (buffer) {
2019-02-21 13:24:29 +00:00
try {
json = JSON.parse(Buffer.concat([buffer, chunk]));
} catch (e) {
/* res.close calls onAborted */
res.close();
return;
}
cb(json);
2019-02-20 22:19:30 +00:00
} else {
2019-02-21 13:24:29 +00:00
try {
json = JSON.parse(chunk);
} catch (e) {
/* res.close calls onAborted */
res.close();
return;
}
cb(json);
2019-02-20 22:19:30 +00:00
}
} else {
if (buffer) {
buffer = Buffer.concat([buffer, chunk]);
} else {
buffer = Buffer.concat([chunk]);
}
}
});
/* Register error cb */
res.onAborted(err);
}