如何为本地提供的JSON文件创建Web服务终结点 [英] How can I create a web service endpoint for a locally served JSON file

查看:113
本文介绍了如何为本地提供的JSON文件创建Web服务终结点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究React.js教程,网址为: http://facebook.github.io/react/docs/tutorial.html

I'm working through the React.js tutorial found here: http://facebook.github.io/react/docs/tutorial.html

当使用AJAX和post方法向页面添加评论时,我得到501 (Unsupported method ('POST')).

When adding comments to the page using AJAX and the post method, I get 501 (Unsupported method ('POST')).

我知道您无法在本地发送JSON post命令(类似于此问题:

I know you can't send a JSON post command locally (similar to this question: angularjs $http.post results in 501 Unsupported method ('POST')) and I'm using python -m SimpleHTTPServer.

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

How do I set up a web service endpoint for the JSON file?

推荐答案

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

If you look at reactjs/react-tutorial on github, there's an example server using node.js:

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

这是server.js文件.

Here's the server.js file.

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.
 */

这篇关于如何为本地提供的JSON文件创建Web服务终结点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆