在没有其他软件包的情况下在Meteor + React上创建REST API

时间:2015-09-08 16:35:58

标签: json reactjs meteor url-routing

例如,当路径为

/json/users/4

meteor app必须返回类似

的json
{
    id: 4,
    name: 'Alex'
}

我使用 reactrouter:react-router 进行客户端路由。我知道 reactrouter:react-router-ssr ,但是如何使用它来响应原始json?并使其与现有客户端路由不冲突?

1 个答案:

答案 0 :(得分:2)

我找到了答案。 Meteor的默认 Webapp 包将有助于(doc):

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

我把它放在服务器文件夹中。其他路线将按原样呈现。
所以,有更多有用的例子(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 可用于获取 GET 参数。