【问题标题】:How can I create a web service endpoint for a locally served JSON file如何为本地提供的 JSON 文件创建 Web 服务端点
【发布时间】:2014-11-21 18:12:06
【问题描述】:

我正在学习此处的 React.js 教程:http://facebook.github.io/react/docs/tutorial.html

使用 AJAX 和 post 方法将 cmets 添加到页面时,我得到501 (Unsupported method ('POST'))

我知道你不能在本地发送 JSON post 命令(类似于这个问题:angularjs $http.post results in 501 Unsupported method ('POST')),我正在使用python -m SimpleHTTPServer

如何为 JSON 文件设置 Web 服务端点?

【问题讨论】:

    标签: json reactjs


    【解决方案1】:

    如果你查看 github 上的 reactjs/react-tutorial,有一个使用 node.js 的示例服务器:

    git clone git@github.com:reactjs/react-tutorial.git && cd react-tutorial
    npm install
    node server.js
    

    这是 server.js 文件。

    var fs = require('fs');
    var path = require('path');
    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    
    var comments = JSON.parse(fs.readFileSync('_comments.json'));
    
    app.use('/', express.static(path.join(__dirname, 'public')));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));
    
    app.get('/comments.json', function(req, res) {
      res.setHeader('Content-Type', 'application/json');
      res.send(JSON.stringify(comments));
    });
    
    app.post('/comments.json', function(req, res) {
      comments.push(req.body);
      res.setHeader('Content-Type', 'application/json');
      res.send(JSON.stringify(comments));
    });
    
    app.listen(3000);
    
    console.log('Server started: http://localhost:3000/');
    
    /**
     * This file provided by Facebook is for non-commercial testing and evaluation purposes only.
     * Facebook reserves all rights not expressly granted.
     *
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
     * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
     * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
     * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     */
    

    【讨论】:

    • 谢谢!还需要注意的是,这个 repo 使用了 React 0.8,所以教程做了一些改动,但是使用带有 express 服务器的节点就可以了。
    • github.com/reactjs/react-tutorial 是 tutorial-in-a-repo 的新家。
    • 我知道你很高兴,但如果其他人在我们更新之前看到这个,我添加了其他几种语言(python、ruby)的服务器,如果 node.js 不是' t 你的东西 :) 查看 PR(并随时添加其他语言的建议!) - github.com/reactjs/react-tutorial/pull/5
    猜你喜欢
    • 1970-01-01
    • 2012-01-26
    • 2012-01-17
    • 2011-07-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    相关资源
    最近更新 更多