首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为本地服务的JSON文件创建web服务端点

如何为本地服务的JSON文件创建web服务端点
EN

Stack Overflow用户
提问于 2014-09-26 16:52:31
回答 1查看 3.2K关注 0票数 1

我正在研究在这里找到的React.js教程:http://facebook.github.io/react/docs/tutorial.html

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

我知道您不能在本地发送JSON命令(类似于这个问题:angularjs $http.post导致501个不支持的方法('POST')),我正在使用python -m SimpleHTTPServer

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-26 17:42:28

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

代码语言:javascript
复制
git clone git@github.com:reactjs/react-tutorial.git && cd react-tutorial
npm install
node server.js

这是server.js文件。

代码语言:javascript
复制
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.
 */
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26064533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档