我正在学习此处的 React.js 教程:http://facebook.github.io/react/docs/tutorial.html
使用 AJAX 和 post 方法向页面添加评论时,我收到 501(不支持的方法('POST'))
。
我知道您无法在本地发送 JSON post 命令(类似于此问题: angularjs $http.post results in 501 Unsupported method ('POST') ),并且我正在使用 python -m SimpleHTTPServer
。
如何为 JSON 文件设置 Web 服务端点?
最佳答案
如果你看reactjs/react-tutorial在 github 上,有一个使用 node.js 的示例服务器:
git clone <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f2959b86b2959b869a8790dc919d9f" rel="noreferrer noopener nofollow">[email protected]</a>: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.
*/
关于json - 如何为本地服务的 JSON 文件创建 Web 服务端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26064533/