Closed nacimgoura closed 7 years ago
Hello @nacimgoura ,
Thank you for the question 😄 No.
But it's possible with pure Meteor, without any additional packages, using internal webapp
package.
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
const bound = Meteor.bindEnvironment((callback) => { callback(); });
WebApp.connectHandlers.use(function(request, response, next) {
// Let's assume JSON was sent in POST request to '/api/form/post'
if (!!~request._parsedUrl.path.indexOf('/api/form/post') && request.method === 'POST') {
let body = '';
request.on('data', (data) => {
bound(() => {
body += data;
});
});
request.on('end', () => {
bound(() => {
// Decode received JSON (maybe it's safer to wrap into `try.. catch..`)
const data = JSON.parse(body);
// Response (reply):
const result = JSON.stringify({status: 'OK'});
if (!response.headersSent) {
response.writeHead(200, {
'Content-Length': result.length,
'Content-Type': 'application/json'
});
}
if (!response.finished) {
response.end(data);
}
});
});
} else {
// Serve request normally
next();
}
});
Thank you for your reply :smile:
@nacimgoura hope it helped you.
Please, support this project by:
With this method when I do JSON.parse(body)
, I have the error unexpected number
And I can't solve it :disappointed:
@nacimgoura could you print body
into console:
console.log(body);
How do you submit POST data? Make sure it's JSON not a x-url-encoded-form.
Sorry for the late reply. In your example, text and http are undefined and when I replace I have an error with JSON. parse (). I do this :
WebApp.connectHandlers.use('/hello', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.writeHead(200);
const json = req.body;
console.log(json);
res.end(json);
});
json is always undefined. Is there any manipulation to do beforehand? Thank you for your help :+1:
@nacimgoura whoops, you're right... Fixed, thank you.
req
has no body
option. body
can be obtained from data
event:
WebApp.connectHandlers.use(function(request, response, next) {
let body = '';
request.on('data', (data) => {
bound(() => {
body += data;
});
});
});
See my updated answer.
Thank you, it works :smile: And it is possible to retrieve in JSON format?
It depends from how you send data. How do you send POST request?
I send it with a form with method="post".
Ok, in this scenario it uses application/x-www-form-urlencoded
encoding (or format).
So, you receive something like: MyVariableOne=ValueOne&MyVariableTwo=ValueTwo
.
Quick way to parse it:
const JSONbody = JSON.parse('{"' + decodeURI(request._parsedUrl.query).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}');
All right, thank you :wink: I close this issue!
Hello, Is it possible to retrieve data in post with flow router? Thanks for your reply :smile: