veliovgroup / flow-router

🚦 Carefully extended flow-router for Meteor
https://packosphere.com/ostrio/flow-router-extra
BSD 3-Clause "New" or "Revised" License
202 stars 29 forks source link

method post #20

Closed nacimgoura closed 7 years ago

nacimgoura commented 7 years ago

Hello, Is it possible to retrieve data in post with flow router? Thanks for your reply :smile:

dr-dimitru commented 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();
  }
});
nacimgoura commented 7 years ago

Thank you for your reply :smile:

dr-dimitru commented 7 years ago

@nacimgoura hope it helped you.

Please, support this project by:

nacimgoura commented 7 years ago

With this method when I do JSON.parse(body), I have the error unexpected number And I can't solve it :disappointed:

dr-dimitru commented 7 years ago

@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.

nacimgoura commented 7 years ago

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:

dr-dimitru commented 7 years ago

@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.

nacimgoura commented 7 years ago

Thank you, it works :smile: And it is possible to retrieve in JSON format?

dr-dimitru commented 7 years ago

It depends from how you send data. How do you send POST request?

nacimgoura commented 7 years ago

I send it with a form with method="post".

dr-dimitru commented 7 years ago

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, '":"') + '"}');
nacimgoura commented 7 years ago

All right, thank you :wink: I close this issue!