Make REST API on Meteor+React without other packages

久未见 提交于 2019-12-23 01:29:13

问题


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:


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.



来源:https://stackoverflow.com/questions/32462946/make-rest-api-on-meteorreact-without-other-packages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!