Make REST API on Meteor+React without other packag

2019-06-02 07:07发布

For example, when the path is

/json/users/4

meteor app must return json something like

{
    id: 4,
    name: 'Alex'
}

I'm using reactrouter:react-router for client routing. I know about reactrouter:react-router-ssr, but how to use it to response raw json? And make it not conflicting with existing client routing?

1条回答
乱世女痞
2楼-- · 2019-06-02 07:19

I found the answer. Meteor's default Webapp package will help (doc):

WebApp.connectHandlers.use("/hello", function(req, res, next) {
    res.writeHead(200);
    res.end("Hello world from: " + Meteor.release);
});

I put this in server folder. Other routes will be rendered as they was.
So, there is more useful example (es6):

WebApp.connectHandlers.use("/payme", function(req, res, next) {
    res.writeHead(200, {'Content-Type': 'application/json'});
    if (req.method === 'POST') {
        req.on('data', (chunk) => {
            const body = chunk.toString();
            if (body.length < 1e6) {
                const params = body.split('&').reduce((result, item) => {
                   const [key, val] = item.split('=');
                   //do it for utf-8 values (I use it for cyrillic strings)
                   result[key] = unescape(decodeURI(val)).replace(/\+/g, ' ');
                   return result;
                }, {});                      //post method params

                //do something and get resulting json

                res.end(JSON.stringify(result));
             } else
                 res.end(JSON.stringify({error: 'too big query'}));
        });
    } else
        res.end(JSON.stringify({error: 'isnt post req'}));
});

req.query can be used to get GET params.

查看更多
登录 后发表回答